【问题标题】:NodeJS & ReactJS: FormData is not workingNodeJS 和 ReactJS:FormData 不工作
【发布时间】:2019-09-04 18:21:25
【问题描述】:

您好,我正在尝试向服务器发送数据,但它不起作用并返回未定义

这是我尝试过的

客户:

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 安装了表单数据,并且我正在将它导入到我的代码中,但我无法得到什么是问题

【问题讨论】:

  • 那是什么路由器?你在使用 Express.JS 吗?您使用的是什么正文解析器?
  • 是 express JS,因为我知道 hapi js 路由与 express 不同,如果你的意思是我的正文解析器配置,我已经完美地完成了,因为在其他页面中它可以工作
  • “在其他页面上工作”通常意味着“对于 this 页面的情况是错误的”。提供minimal reproducible example./
  • app.use(bodyParser.urlencoded({extended: false })) app.use(bodyParser.json())
  • 是的,你的身体解析器错了。

标签: javascript node.js reactjs axios form-data


【解决方案1】:

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

此外,您尝试将各个字符串与+ 连接起来,但这不一定有效。试试

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

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

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

这会将参数转换为一个对象,并且还会显示它们的名称。

【讨论】:

  • 我说当我单独登录时它返回未定义的值,并且我有路由配置 router.use('/api/post-recipe', require('file'))
【解决方案2】:
  1. 您似乎正在向/api/post-recipe/ 发布数据,但在/ 路由上查找它
  2. 您正在记录以控制变量数学总和的结果 - 单独记录它们或进一步阅读on MDN

【讨论】:

  • 我说当我单独记录时它返回未定义的值,并且我有路由配置router.use('/api/post-recipe', require('file'))
猜你喜欢
  • 1970-01-01
  • 2014-11-22
  • 2015-06-12
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2023-03-23
  • 2016-11-30
  • 1970-01-01
相关资源
最近更新 更多