如何将表单数据从React发送到Node

如何将表单数据从React发送到Node

本文介绍了如何将表单数据从React发送到Node JS后端服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将FormData从React JS发送到后端(express节点服务器),如下所示.

I am trying to send the FormData from React JS to the backend (express node server) as shown below.

我看到 req.body.myFormData(expressTest.js)的值为空.我也尝试了这篇文章中的建议,但没有运气.感谢您的帮助.

I am seeing the empty value for req.body.myFormData (expressTest.js).I tried the suggestions from this post too but no luck. Any help is appreciated.

如何从React js axios发布请求将FormData发送到节点服务器?

reactTest.js模块

reactTest.js module

myFormData = new FormData();
myFormData.append("userName","TestUser")
myFormData.append("files", file) // input type file
export const sendDocument = async (myFormData) => {
  return await axios({
    method: 'post',
    url: `/sendDocument`,
    data: myFormData,
    headers: { 'Content-Type': 'multipart/form-data' }
  });
};

expressTest.js

expressTest.js

const express = require('express')
const axios = require('axios')
const router = express.Router()

router.post('/', (req, res) => {
  console.log(req.body.myFormData) //giving undefined //tried req.myFormData too
  console.log(JSON.parse(req.body.myFormData.userName))
  axios({
    method: 'post',
    url: '/sendMyUserData',
    data: req.body.myFormData,
    headers: {
      apiKey: 'keytoapi',
      'Content-Type': 'multipart/form-data'
    }
  })
    .then(response => {

      return res.send(res)
    })
    .catch(error => {
      console.error('error')
     }

在添加了@ con-fused和@Kidas推荐的 multer 之后,我可以在Express路由器中读取FormData.

After adding the multer, recommended by @con-fused and @Kidas, I can read the FormData in the Express router.

下面是输出.

console.log(req.body)

[Object: null prototype] {
  files: '[object File]',
  userName: 'TestUser'
}

现在我需要将其发送到后端Java端点-我发送正确的正文吗?它没有达到我的终点

Now I need to send this to my backend Java end point-Am I sending the right body? it is not hitting my endpoint

@PostMapping(path = "/sendMyUserData", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
        public String uploadMyUserData(@RequestPart(value = "files") final MultipartFile[] multipartFiles, @RequestPart(value = "userName", required = true) String userName ) {
            return myService.storeFiles(multipartFiles, userName));
    }

推荐答案

您需要使用multer才能获得multipart/form-data.

You need multer to get the multipart/form-data.

npm i multer

formdataParser = require('multer')().fields([])
app.use(formdataParser)

根据

https://github.com/expressjs/body-parser/issues/88#issuecomment-173644716 评论

这篇关于如何将表单数据从React发送到Node JS后端服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:08