nodejs获取post请求发送的formData数据

前端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

原文地址:https://www.cnblogs.com/web-wjg/p/9244074.html