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(); 2 xhr.open('POST','/test'); 3 // xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); 4 // xhr.send(`name=${username}&&password=${password}`); 5 xhr.setRequestHeader('content-type', 'application/json'); 6 xhr.send(JSON.stringify({username, password}))

express本身只能用get方法,对用post方法的请求, 没法查看request的啥. 所以用第三方插件body-parser;

 1 const bodyParser = require('body-parser');
 2 const app = express();
 3 // var urlencodedParser = bodyParser.urlencoded({ extended: false });
 4 // app.post('/test',urlencodedParser,(req,res)=>{
 5 //     console.log(req.body)
 6 // })
 7 
 8 var jsonParser = bodyParser.json();
 9 app.post('/test',jsonParser,(req,res)=>{
10     console.log(req.body)
11 })

猜你喜欢

转载自www.cnblogs.com/dangdanghepingping/p/11027536.html