Search code examples
javascriptnode.jsreactjsmernreact-fullstack

Axios POST Request Gives 400 (Bad Request) Error on React


When I use the postman backend it works fine. But when using React and trying to add data to the database gives a 400 error.

When I use the console.log(newpost) it gives a new post object on the console. But I can't send the data to the database. How to fix this?

postman image

My React Code:

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>

    )
}

Solution

  • As per your postman's request, the request body is not correctly being passed from react code.The expected key name doesn't match. You need to change newpost variable as follows:

     const newpost = {
                topic,
                description: dec,
                postCategory: cate
            }