400 BAD REQUEST when POST using Axios in React

Tags: , , , ,



Can any help me with this?

I keep getting a 400 bad request from Axios.

I can pass a GET request and confirm its working fine.

I create http-common.js file with following code:

import axios from 'axios';

export default axios.create({
    baseURL: 'https://5fa97367c9b4e90016e6a7ec.mockapi.io/api',
    headers: {
        'Content-type': 'application/json'
    }
});

Then,I create a service that uses axios object above to send HTTP requests.

TodoService.js

import http from '../http-common/http-common';

const getAll=()=>{
    return http.get('/todos');
};

const get=id=>{
    return http.get(`/todos/${id}`);
};

const create=data=> {
    return http.post('/todos',data);
};

const update=(id,data)=>{
    return http.put(`/todos/${id}`,data);
};

const remove = id => {
    return http.delete(`/todos/${id}`);
  };
  
const removeAll = () => {
    return http.delete(`/todos`);
  };
  
const findByTitle = title => {
    return http.get(`/todos?title=${title}`);
  };

  export default {getAll,get,create,update,remove,removeAll,findByTitle};

Then, I use TodoDataService.create(data) … in AddTodos component.

AddTodos.js

import React, { useState } from 'react';
import TodoDataService from '../services/TodoService';

const AddTodos = () => {

    const initialTodoState={
        id:null,
        title: '',
        isDone: false,
        user: ''
    };

    const [todo,setTodo]=useState(initialTodoState);
    const [submitted,setSubmitted]=useState(false);

    const handleInputChange=event=>{
        const {name,value}=event.target;
        setTodo({...todo,[name]:value});
    };

    const saveTodo =()=>{
        var data={
            title: todo.title,
            isDone:todo.isDone,
            user: todo.user
            
        };
        console.log(data);

        TodoDataService.create(data)
        .then(response => {
            setTodo({
                id:response.data.id,
                title: response.data.title,
                isDone: response.data.isDone,
                user: response.data.user
            });
            setSubmitted(true);
            console.log(response.data);
        })
        .catch(e => {
            console.log(e);
        });
    };

    const newTodo=()=>{
        setTodo(initialTodoState);
        setSubmitted(false);
    };

    return (
        <div className="submit-form">
      {submitted ? (
        <div> //...
      ) : (
        <div>
          <div className="form-group"> //...  </div>
          
          <div className="form-group"> //...  </div>

          <button onClick={saveTodo} className="btn btn-success">
            Submit
          </button>
        </div>
      )}
    </div>
    )
}

export default AddTodos;

When clicked Submit it’s giving this error:

enter image description here

Answer

I recreate your api call and got this response:

await fetch('https://5fa97367c9b4e90016e6a7ec.mockapi.io/api/todos', {
method: 'POST', body: JSON.stringify({id: "123",title: "homework", isDone: false, user: "foo"})})
      .then(response => response.json())
      .then(data => {
      console.log(data) 
      })

error 400 "Max number of elements reached for this resource!"

you need to delete some records in order to insert new ones

so after deleting a record:

await fetch('https://5fa97367c9b4e90016e6a7ec.mockapi.io/api/todos/1', {
method: 'DELETE'})
      .then(response => response.json())
      .then(data => {
      console.log(data) 
      })

VM623:5 {id: “1”, title: “deneme”, isDone: true, user: “cafererensimsek”}

and posting a new one, now it works



Source: stackoverflow