React中Axios POST请求返回400错误,Postman可正常请求
解决React中Axios POST请求返回400 Bad Request的问题
问题描述
使用Postman调用后端接口时一切正常,数据可正常存入数据库,但在React项目中通过Axios发送POST请求时返回400(Bad Request)错误。控制台执行console.log(newpost)能正常输出post对象,但数据无法发送到数据库。
Postman请求截图:
React代码:
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> ) }
解决步骤
1. 修正请求体字段名(最可能的原因)
从表单标签可以看出,后端期望的字段应为topic、description、postCategory,但代码中用了简写的dec和cate,导致后端无法识别字段,返回400错误。修改newpost的字段名:
const newpost = { topic, description: dec, // 对应表单的description postCategory: cate // 对应表单的postCategory }
2. 确保请求头Content-Type正确
虽然Axios默认会为POST请求设置Content-Type: application/json,但手动指定可避免配置异常:
axios.post("http://localhost:8000/post/save", newpost, { headers: { 'Content-Type': 'application/json' } })
3. 修正输入框type属性错误
代码中所有输入框的type="test"是语法错误,应改为type="text":
<input type="text" className="form-control" id="name" aria-describedby="emailHelp" onChange={(e)=>{ setTopic(e.target.value) }} />
4. 查看详细错误信息定位问题
在catch回调中打印后端返回的具体错误详情,能更精准定位问题:
.catch((err)=>{ console.log(err.response.data); // 打印后端返回的错误详情 alert(`提交失败:${err.response.data.message || err.message}`) })
内容的提问来源于stack exchange,提问作者Sandaru Jayathilaka
相关产品推荐
相关产品推荐

