Home > Software design >  Axios POST Request Gives 400 (Bad Request) Error on React
Axios POST Request Gives 400 (Bad Request) Error on React

Time:12-23

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>

    )
}

CodePudding user response:

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
        }

CodePudding user response:

Try adding named keys.

For example:

const newpost = {
  topic: 'test',
  dec: 'test',
  cate: 'test'
}

CodePudding user response:

please post the 400 bad request message, this might be related to your backend routes , You should be looking for errors in the backend

  • Related