NodeJS和ReactJS:FormData无法正常工作

问题描述 投票:-2回答:2

您好我正在尝试将数据发送到服务器但它不起作用并返回undefined

这是我尝试过的

客户:

var Data = new FormData();
    Data.append('name', this.state.name);
    Data.append('time', this.state.time);
    Data.append('portion', this.state.portion);
    Data.append('method', this.state.method);
    Data.append('tags', JSON.stringify(this.state.tags));
    Data.append('ingredients', JSON.stringify(this.state.ingredients))
    Data.append('level', this.state.level)
console.log(Data)
axios.post('/api/post-recipe', Data)
 .then(res => res.data)
 .then(data =>{
      console.log(data.dish)
 })
 .catch(err => {
    if(err.response){
        if(err.response.data.redirect === true){
            window.location.replace(err.response.data.location)
        }
        if(err.response.data.message){
        alert(err.response.data.message)
        }
    }
 })

服务器:

  router.post('/', async (req, res) => {
    try {

        const {
             name,
             time,
             portion,
             ingredients,
             method,
             level,
             tags
                 } = req.body

console.log(name + time + portion + ingredients + method + level + tags)

} catch (error) {
 return res.status(500).send({
  message: error.message
   })
  }
})

它在控制台中记录NaN,如果我在'name: ' name等控制台中添加单词,它会记录未定义的值,我已经从npm安装了表单数据,我将其导入到我的代码中,我无法得到什么问题

javascript node.js reactjs axios form-data
2个回答
0
投票
  1. 您似乎将数据发布到/api/post-recipe/,但在路线/上寻找它
  2. 您正在登录控制变量数学总和的结果 - 单独记录或进一步阅读on MDN

0
投票

您将数据发送到(/api/post-recipe)的路由与您处理它的服务器(/)上的路由不匹配。您必须在客户端中更改对axios的调用,或者您必须在服务器上调整路由定义以匹配/api/post-recipe

此外,您尝试使用+连接各个字符串,但这不一定有效。尝试

console.log(name, time, ...);

相反,并为...输入其他变量。如果您还想知道变量的名称,而不仅仅是它们的值,请将所有参数封装到一对大括号中的console.log中:

console.log({ name, time, ... });

这会将参数转换为对象,并显示其名称。

© www.soinside.com 2019 - 2024. All rights reserved.