AxiosError : Request failed with status code 400 (in React JS)

Viewed 8020

I am trying to post comments using axios. When I submit my datas entered in the form, I see this error in the console :

AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

Here is my code :

import React, { useState } from 'react'
import TextField from '@material-ui/core/TextField';
import { Button } from '@material-ui/core'
import CommentsAPI from '../../Services/CommentsAPI'

export default function CommentForm() {

    const [comment, setComment] = useState({})

    const handleSubmit = async (event) => {
        event.preventDefault();
        try {
            const data = CommentsAPI.create(JSON.stringify(comment))
            console.log(data)
        } catch (error) {
            console.log(error)
        }
    }

    const handleChange = (event) => {
        const {name, value} = event.currentTarget
        setComment({
            ...comment,
            [name]: value
        })
    }

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <TextField 
                    id="pseudo" 
                    label="Pseudo" 
                    type="text" 
                    onChange={handleChange}
                    name="pseudo"
                />
            </div>
            <div>
                <TextField
                    id="outlined-multiline-static"
                    label="Comment"
                    multiline
                    minRows={2}
                    onChange={handleChange}
                    name="content"
                />
            </div>
            <div>
                <Button variant="contained" color="primary" type="submit">
                    Send
                </Button>
            </div>
        </form>
    )
}

CommentsAPI.js file :

import { URL_COMMENTS } from '../config'
import axios from 'axios'

function create(comment) {
    return axios.post(URL_COMMENTS, comment)
}

const CommentsAPI = {
    create
}

export default CommentsAPI

I am trying to understand what is wrong. Thank you very much for your help !

Have a look on my server :

Collection type

Permission with POST api url

4 Answers

Your problem is here...

JSON.stringify(comment)

This passes a string to Axios which it will interpret as text/plain and set the request content-type header to the same.

It's highly likely your API expects an application/json or application/x-www-form-urlencoded request body and rejects a plain text one.

To send the former, simply omit JSON.stringify() and let Axios deal with serialisation and content-type detection

// don't forget to `await`
const { data } = await CommentsAPI.create(comment);

The latter can be achieved using URLSearchParams

const { data } = await CommentsAPI.create(new URLSearchParams(comment));

You're not sending anything to your API. CommentsAPI.create(YOUR COMMENT HERE)

const handleSubmit = async (event) => {
    event.preventDefault();
    try {
        // const data = CommentsAPI.create() // WRONG !
        // Create expects a comment, send something !
        const data = CommentsAPI.create('This is a test');
        // Or send the valu in your state
        // const data = CommentsAPI.create(comment.content);
    } catch (error) {
        console.log(error)
    }
}

Also, in your server you will need to return helpful error message. Like 'Hey, there is no message, please send a message in the payload'. That will help you understand better what's going on.

For anyone else, who is facing the same issue, try changing your get http request to post, if you are sending data from body that has a list. Hope this helps.

If you receive a 400 (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_client_errors), it means that the sever received your request but the content was not valid. Read the documentation of the API to be sure you send the correct payload.

By default, if Axios receives something other than a 2xx, it will throw an exception

And if you want your

console.log(data)

to work, do not forget to add await:

await console.log(data)

so that the code awaits the answer of the server before trying to console.log() it

Related