• 【转】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

  • 相关阅读:
    新年新气象,用新年的喜庆来迎接的生活
    vs2005中如何发布网站及打包web项目生成安装文件
    完整打印页面控件的解决方案
    vi使用体会
    向ATL DLL中传递C++对象
    CentOS 5.3配置软件源以及CVS服务器
    堆上多维数组的内存管理
    物理坐标与逻辑坐标
    好友列表的实现
    在STL中处理对象指针
  • 原文地址:https://www.cnblogs.com/mmzuo-798/p/11158467.html
Copyright © 2020-2023  润新知