所以我正在嘗試制作一個添加訂單頁面表單,該表單應該將資料提交到用戶的訂單 [] 集合 (mongoDB) 中。
后端作業得很好并且完全符合它的意圖,但前端表單只提交空資料,盡管請求狀態為 200。
這是表格
export default function OrderForm() {
const [email, setEmail] = useState('')
const [ticker, setTicker] = useState('')
const [amount, setAmount] = useState('')
const [price, setPrice] = useState('')
const [date, setDate] = useState('')
const [comments, setComments] = useState('')
const handleSubmit = async(value) =>{
value.preventDefault()
const orders = {
ticker: ticker,
amount: amount,
price: price,
date: date,
comments: comments
}
console.log(orders)
try{
axios.put(`http://localhost:8081/api/auth/order/:email?=${email}`, {
data: orders
})
.then((res) => {
if(res){
console.log(res)
console.log(`Order saved to ${email}'s account`)
}
}).catch(e =>{
console.log(e)
})
}catch(error){
console.error(error)
}
}
表單輸出: 表單的控制臺日志
這是我用 Postman 測驗時有效的后端代碼:
exports.addOrder = async (req, res) => {
const {email} = req.params
const {
ticker,
amount,
price,
date,
comments
} = req.body;
try{
const user = await User.findOneAndUpdate({
email: email
}, {
$push: {
orders: {
ticker: ticker,
amount: amount,
price: price,
date: date,
comments: comments
}
},
})
if (!user) {
console.log('Sorry that user does not exist')
}
res.status(200).send(user).json({
message: `Order: ${orders} \n has been added to ${user}`
});
}catch(error) {
res.status(400).json({
error: error.message
})
}
}
uj5u.com熱心網友回復:
您正在使用 url as http://localhost:8081/api/auth/order/:email?=${email},您必須使用http://localhost:8081/api/auth/order/${email}
有關更多資訊:(https://v5.reactrouter.com/web/example/query-parameters)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/369055.html
