前端post請求發送formData的類型數據時,需要服務端引入中間件body-parser,主要原因是post請求發送的數據,是在http的body里面,所以需要進行解析,否則獲取不到數據(數據為空)
注意:對於使用Requst Payload(以“流“的方式傳遞數據時,不要要這個中間件)
即便是前端瀏覽器能夠看到數據(如下圖所示)已發送並且請求成功,status==200;
前端代碼:
let forms= new FormData(); forms.append('uname','test'); forms.append('psd',123456); forms.append('age','22'); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState==4){ if(xhr.status>=200&&xhr.status<=300||xhr.status==304){ console.log(xhr.response) } }else{ console.log(xhr.status) } } xhr.open('POST','http://localhost:99/formdata',true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //formdata數據請求頭需設置為application/x-www-form-urlencoded
console.log(forms);
xhr.send(forms);
后端node.js代碼:
let express = require('express'); let app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json());//數據JSON類型 app.use(bodyParser.urlencoded({ extended: false }));//解析post請求數據 app.all('*',function(req,res,next){ let origin=req.headers.origin; res.setHeader('Access-Control-Allow-Origin',"*"); res.setHeader('Access-Control-Allow-Headers','Content-Type'); next(); }) app.post('/formdata',function(req,res){ console.log(req.body); res.send('POST發送成功了') }) app.listen(99);
其中三行代碼很關鍵:
const bodyParser = require('body-parser'); app.use(bodyParser.json());//數據JSON類型 app.use(bodyParser.urlencoded({ extended: false }));//解析post請求數據
加入這三行代碼,既可以在req.body內打印出前端請求的formdata數據
關於body-parser介紹比較詳細的一個網站:https://www.cnblogs.com/chyingp/p/nodejs-learning-express-body-parser.html