Emilie Tossan
Emilie Tossan

Reputation: 85

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

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

Upvotes: 9

Views: 82739

Answers (6)

Mandar Parekh
Mandar Parekh

Reputation: 1

Sometimes when you clone git repos then you need to install all the required dependencies in react and in backend if required but if it generates error while making axios request from frontend try byrunning this command

npm install axios react react-dom react-scripts web-vitals

Upvotes: -1

Tushar Kumar
Tushar Kumar

Reputation: 1

In my case it was, I did not mention (proxy) in package.json

Upvotes: -1

Phil
Phil

Reputation: 164946

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));

Upvotes: 0

David Alvarez
David Alvarez

Reputation: 1286

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

Upvotes: 0

Sakar Poudel
Sakar Poudel

Reputation: 11

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.

Upvotes: 0

Zied Hf
Zied Hf

Reputation: 581

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.

Upvotes: 2

Related Questions