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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM