var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//说明下:因为下面要用到res.body获取到前端传过来的参数,用res.body的前提是首先导入body-parser
//跨域处理:
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});
//通过这个处理后会允许前端任何方式的跨域请求
//前端页面index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<scriptsrc="//cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({url:'http://localhost:4000/list',
processData: false,
cache:false,
contentType: "application/json; charset=utf-8",
data:JSON.stringify({page:1,pageSize:10,classify_id:77}),
datatype: "json",
type: 'post',
success: function (res) {
console.log(res)
},error:function (res) {
}
})
</script>
</body>
</html>
//后端处理
app.post('/list', function (req, res) {
console.log(req.body)
//这时可以看到控制台输出了:前端传过来的参数{page:1,pageSize:10,classify_id:77}
});
搞定!!!!