码迷,mamicode.com
首页 > Web开发 > 详细

ajax 的post方法 的content-type设置和express里应用body-parser

时间:2019-06-15 15:40:33      阅读:386      评论:0      收藏:0      [点我收藏+]

标签:The   span   OLE   false   ext   set   ESS   password   方法   

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 })

 

ajax 的post方法 的content-type设置和express里应用body-parser

标签:The   span   OLE   false   ext   set   ESS   password   方法   

原文地址:https://www.cnblogs.com/dangdanghepingping/p/11027536.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!