nodejs獲取post請求發送的formData數據

前端post請求發送formData的類型數據時,須要服務端引入中間件body-parser,主要緣由是post請求發送的數據,是在http的body裏面,因此須要進行解析,不然獲取不到數據(數據爲空)html

注意:對於使用Requst Payload(以「流「的方式傳遞數據時,不要要這個中間件)前端

即使是前端瀏覽器可以看到數據(以下圖所示)已發送而且請求成功,status==200;node

 前端代碼:express

  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代碼:npm

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

其中三行代碼很關鍵:json

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瀏覽器

相關文章
相關標籤/搜索