nodejs寫api給前端調(diào)用

1.npm init 生成package.json文件

2. 安裝依賴

npm install express –save

npm install body-parser –save


服務(wù)器端

app.js

var express=require('express');

var app =express();

var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json

app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.all('*', function(req, res, next) {

? ? res.header("Access-Control-Allow-Origin", "*");

? ? res.header("Access-Control-Allow-Headers", "X-Requested-With");

? ? res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");

? ? res.header("X-Powered-By",' 3.2.1');

? ? res.header("Content-Type", "application/json;charset=utf-8");

? ? next();

});

var questions=[

? ? {

? ? data:213,

? ? num:444,

? ? age:12

? ? },

? ? {

? ? data:456,

? ? num:678,

? ? age:13

? ? }];

//寫個(gè)接口123

app.get('/123',function(req,res){

? ? res.status(200),

? ? res.json(questions)

? ? });

app.post('/wdltest',function(req,res){

? ? console.log(req.stack);

? ? console.log(req.body);

? ? console.log(req.url);

? ? console.log(req.query);

? ? res.json(req.body)

})

//配置服務(wù)端口

var server = app.listen(3001, function () {

? ? var host = server.address().address;

? ? var port = server.address().port;

? ? ? ? console.log('Example app listening at http://%s:%s', host, port);

? ? })


//前端調(diào)用

index.html

<!DOCTYPE html>

<html lang="en">

<head>

? ? <meta charset="UTF-8">

? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">

? ? <meta http-equiv="X-UA-Compatible" content="ie=edge">

? ? <title>Document</title>

? ?  <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

</head>

<body>

? ? <script>

? ? ? ? $(function(){

? ? ? ? ? ? console.log(1);

? ? ? ? ? ? //get請(qǐng)求

? ? ? ? ? ? $.ajax({

? ? ? ? ? ? ? ? type:'get',

? ? ? ? ? ? ? ? url:'http://localhost:3001/123',

? ? ? ? ? ? ? ? success:function(data){

? ? ? ? ? ? ? ? ? ? console.log(data);

? ? ? ? ? ? ? ? },

? ? ? ? ? ? ? ? error:function(err){

? ? ? ? ? ? ? ? ? ? console.log(err)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? })

? ? ? ? ? ? //post請(qǐng)求

? ? ? ? ? ? $.ajax({

? ? ? ? ? ? ? ? type:'post',

? ? ? ? ? ? ? ? url:'http://localhost:3001/wdltest',

? ? ? ? ? ? ? ? data:{name:'wdl',pass:'123'},

? ? ? ? ? ? ? ? success:function(data){

? ? ? ? ? ? ? ? ? ? console.log(data);

? ? ? ? ? ? ? ? },

? ? ? ? ? ? ? ? error:function(err){

? ? ? ? ? ? ? ? ? ? console.log(err)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? })

? ? ? ? })

? ? </script>

</body>

</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容