【问题标题】:React, node js, mongoDB - How to make post, put, delete with FormData?React、node js、mongoDB - 如何使用 FormData 进行发布、放置、删除?
【发布时间】:2019-02-17 16:43:00
【问题描述】:

如何用formdata创建post服务?

我通过 Axios 发送了表单数据。 但是,node-express 服务器上的“req.body.title”的值为空。 所以现在我以以下格式发送 fetch 。 但是我需要将文件上传到服务器,所以我想使用formData发送它。

let bodys = 'title=a1&contents=b'
fetch("http://localhost:5000/test", {
            method : 'post',
            headers : {
                'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: bodys
        })
        .then(function(response){
            console.log('Request Succeded ', response);
        })
        .catch(function (error){
            console.log('Failed ', error)
        })

我使用 append 和 new FormData() 编写了新数据, 我检查了 FormData 是否包含 React 上的值。 但是node-express服务器没有进入body。

请告诉我该怎么做...

【问题讨论】:

    标签: node.js reactjs post fetch axios


    【解决方案1】:

    你只是发送一个字符串,所以

    你可以像下面这样访问你的身体

      let bodys = 'title=a1&contents=b'
     console.log(req.body); //will print title and contents as you are sending
    

    如果要分别访问标题和内容,则必须将数据作为对象发送

      const bodys = {“title”: “a1”, “contents”: “b”}
      console.log(“title”, req.body.title); //will print a1
      console.log(“contents”, req.body.contents); //will print b
    

    查看此线程以获取更多详细信息https://github.com/github/fetch/issues/263

    【讨论】:

      【解决方案2】:

      尝试发送 FormData 对象而不是原始字符串作为您的请求正文。

      const bodys = new FormData();
      
      bodys.append('title', 'a1');
      bodys.append('contents', 'b');
      

      此表单数据将在 express.js 服务器的 request.body 中可用。

      编辑:要解析 express.js 中的 FormData,您需要像 multer 这样的中间件

      const upload = require('multer');
      
      app.use('/', upload.any(), yourRouteHandler);
      

      【讨论】:

      • 正如 oosniss 指出的那样,您需要一些解析 multipart/form-data 的中间件。像 bodyParser 这样的库不处理这种 MIME 类型,因此表单数据不会显示在 req.body 上。
      猜你喜欢
      • 2019-05-30
      • 2021-03-18
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 2019-07-10
      • 2018-09-12
      • 2019-01-13
      • 2018-03-28
      相关资源
      最近更新 更多