【发布时间】: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