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浏览器

相关文章
相关标签/搜索