[英]Axios POST Request Gives 400 (Bad Request) Error on React
当我使用邮递员后端时,它工作正常。 但是当使用 React 并尝试将数据添加到数据库时会出现 400 错误。
当我使用console.log(newpost)
时,它会在控制台上提供一个新的 post 对象。 但是我无法将数据发送到数据库。 如何解决这个问题?
我的反应代码:
import React, {useState} from "react";
import axios from "axios";
export default function AddPost(){
const [topic,setTopic] = useState("")
const [dec,setDec] = useState("")
const [cate,setCate] = useState("")
function sendData(e){
e.preventDefault();
const newpost = {
topic,
dec,
cate
}
axios.post("http://localhost:8000/post/save",newpost)
.then(()=>{
alert("post added")
setTopic ("")
setDec ("")
setCate("")
}).catch((err)=>{
alert(`Not inserted ${err}`)
})
}
return(
<div className="container">
<form onSubmit={sendData} >
<div className="mb-3">
<label htmlFor="name" className="form-label">topic</label>
<input type="test" className="form-control" id="name" aria-describedby="emailHelp" onChange={(e)=>{
setTopic(e.target.value)
}} />
</div>
<div className="mb-3">
<label htmlFor="Age" className="form-label">description</label>
<input type="test" className="form-control" id="Age" onChange={(e)=>{
setDec(e.target.value)
}}/>
</div>
<div className="mb-3">
<label htmlFor="Gender" className="form-label">postCategory</label>
<input type="test" className="form-control" id="Gender" onChange={(e)=>{
setCate(e.target.value)
}}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<div/>
</div>
)
}
尝试添加命名键。
例如:
const newpost = {
topic: 'test',
dec: 'test',
cate: 'test'
}
请发布 400 错误请求消息,这可能与您的后端路由有关,您应该在后端查找错误
您是否检查过标题是否正确?
根据邮递员的要求,请求正文未从反应代码正确传递。预期的键名不匹配。 您需要按如下方式更改newpost
变量:
const newpost = {
topic,
description: dec,
postCategory: cate
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.