[英]Getting Undefined When Passing in FormData to Redux Register Function in Reactjs with NodeJS
[英]NodeJS & ReactJS: FormData is not working
你好,我正在嘗試將數據發送到服務器,但它不起作用並返回未定義
這是我嘗試過的
客戶:
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 安裝了表單數據,我正在將它導入到我的代碼中,但我無法得到什么是問題
/api/post-recipe/
但在路線上尋找它/
您將數據發送到 ( /api/post-recipe
) 的路線與您處理數據的服務器 ( /
) 上的路線不匹配。 您要么必須在客戶端更改對axios
的調用,要么必須調整服務器上的路由定義以匹配/api/post-recipe
。
此外,您嘗試使用+
連接各個字符串,但這不一定有效。 嘗試
console.log(name, time, ...);
相反,並為...
放入其他變量。 如果您還想知道變量的名稱,而不僅僅是它們的值,請將console.log
所有參數封裝在一對花括號中:
console.log({ name, time, ... });
這會將參數轉換為一個對象,並且還會顯示它們的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.