1.npm init 生成package.json文件
2. 安装依赖
npm install express –save
npm install body-parser –save
服务器端
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
}];
//写个接口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)
})
//配置服务端口
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);
})
//前端调用
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请求
$.ajax({
type:'get',
url:'http://localhost:3001/123',
success:function(data){
console.log(data);
},
error:function(err){
console.log(err)
}
})
//post请求
$.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>