Node.js req.body在express.js中发送formdata时返回空对象

Node.js req.body在express.js中发送formdata时返回空对象,node.js,reactjs,express,request,axios,Node.js,Reactjs,Express,Request,Axios,我的问题有点棘手。我知道每个人都会说bodyparser作为解决方案,但我也使用了bodyparser,但我仍然得到相同的错误 这是我的后端服务器.js const fs = require('fs') const path = require('path') const express = require('express') // We import express module in our pro

我的问题有点棘手。我知道每个人都会说bodyparser作为解决方案,但我也使用了bodyparser,但我仍然得到相同的错误

这是我的后端服务器.js

const fs = require('fs')
const path = require('path')
const express = require('express')                                               // We import express module in our project.
const app = express()                                                            // We assign express's functions to app variable.
const bodyParser = require('body-parser')                                        // BodyParser catches data from the http request(POST,PATCH,PUT) and parsing this data to JSON object.
const HttpError =require('./models/HttpError')
const mongoose = require('mongoose')
const userRouter = require('./routes/user-routes')
const recipeRouter = require('./routes/recipe-routes')
const mealPlanRouter = require('./routes/mealplan-routes')

app.use(bodyParser.json())    
app.use(
  bodyParser.urlencoded({
    extended: true
  })
);       
                                                                                // We catch data from request and turn this data to json object with BodyParser.
app.use('/uploads/images', express.static(path.join('uploads','images')))       // We create middleware for uploading images and we called this middleware here.
app.use((req, res, next) => {                                                   // We need to write this middleware. Because We decide to  how to get a request from the client.This is like protocol between server and client for the communication.
  res.setHeader('Access-Control-Allow-Origin','*')
  res.setHeader('Access-Control-Allow-Headers',
                'Origin, X-Request-With, Content-Type, Accept, Authorization'
)
 res.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE')
  next()
})

app.use('/api/users',userRouter)
app.use('/api/recipes',recipeRouter)
app.use('/api/mealplans',mealPlanRouter)

app.use((req, res, next) => {                                                   // When the client try to access wrong routes. We need to say the client is going wrong way.
  const error = new HttpError('Could not find this route', 404)
  throw error
})
app.use((err,req,res,next) => {                                                 // We check if user pick file for importing an image.
  if(req.file){
    fs.unlink(req.file.path, err => {
      console.log(err)
    })
  }
  if(res.headerSent){
    return next(err)
  }
  res.status(err.code || 500)
  res.json({message:err.message || 'Unknown error occured'})
})

 // We connect our project with database. Mongoose communicate with database and we communicate with mongoose. This way is more secure.
mongoose
        .connect(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0-vvtq0.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`,{ useNewUrlParser: true, useUnifiedTopology: true})
        .then(() => {
          app.listen( process.env.PORT || 5000, () => {
            console.log('The Server is running')
          })
        })
        .catch(err => {
          console.log(err)
        })

这是我发送表单数据的地方。我从“网络”选项卡检查表单数据。看起来不错。当我在server.js中用req.body检查formdata时,返回空对象

  const handleSubmit = async e => {
        e.preventDefault()
        const datestr = (new Date(startDate)).toUTCString();
        try{
          const formData = new FormData()
          formData.append('title',formState.inputs.title.value)
          formData.append('date',datestr)
          formData.append('timeFrame',formState.inputs.timeFrame.value)
          formData.append('targetCalories',formState.inputs.targetCalories.value)
          formData.append('diet',formState.inputs.diet.value)
          formData.append('exclude',excludeData.join())
          formData.append('creator',auth.userId)


          const responseData = await axios.post(
            process.env.REACT_APP_BACKEND_URL+'/mealplans/new',
             formData,{
             headers: {Authorization : `Bearer ${auth.token}`} })
             console.log(responseData)

        }
        catch(err){
          console.log(err.message)
        }


    }

从现在起感谢您的帮助。

FormData对象将转换为多部分请求正文

您需要一个能够处理该数据格式的主体解析器。您只有JSON和URL编码数据的正文解析器

主页推荐了4个支持多部件主体的模块