express接受post参数需要引入一个核心模块 body-parser
const bodyParser = require('body-parser')
然后应用到express实例上
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: false}));
前端发送一个post请求,post请求必须要设置请求头的格式。
var ajaxObj = new XMLHttpRequest();
ajaxObj.open("POST", 'http://localhost:8124',true);
ajaxObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
ajaxObj.send("name=zhangsan&age=15");
ajaxObj.onreadystatechange = function () {
if (ajaxObj.readyState == 4 && ajaxObj.status == 200) {
console.log(ajaxObj.responseText)
}
}
这是一个简单的ajax post请求。
express响应设置如下
const express = require('express')
const server = express()
const bodyParser = require('body-parser')
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: false}));
server.post('/',(req,res)=>{
console.log(req.body)
res.header('Access-Control-Allow-Origin','*')
res.send(req.body)
})
server.listen(8124)
console.log('Server running at http://localhost:8124')
完美。