
正文
ajax 的post方法 的content-type设置和express里应用body-parser
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
ajax的post方法相比get方法,在传参形式上很不一样, get把参数用'?'拼接在端口后,并且用'&'连接;而post则是需要在send参数里设置.
根据ajax实例xhr.setRequestHeader('content-type', )中第二个参数的不同, send的参数也不相同.
最常用的有两种: application/x-www-form-encoded 和 application/json两种形式.
1
const username = document.getElementById('username').value,
password = document.getElementById("password").value;
var xhr = new XMLHttpRequest();
xhr.open('POST','/test');
// xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
// xhr.send(`name=${username}&&password=${password}`);
xhr.setRequestHeader('content-type', 'application/json');
xhr.send(JSON.stringify({username, password}))
express本身只能用get方法,对用post方法的请求, 没法查看request的啥. 所以用第三方插件body-parser;
const bodyParser = require('body-parser');
const app = express();
// var urlencodedParser = bodyParser.urlencoded({ extended: false });
// app.post('/test',urlencodedParser,(req,res)=>{
// console.log(req.body)
// }) var jsonParser = bodyParser.json();
app.post('/test',jsonParser,(req,res)=>{
console.log(req.body)
})








