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

6

9

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

Smackdab answered 19/5, 2022 at 15:37 Comment(3)
We can't tell you why the server considers your request to be bad because you haven't told us anything about the server or the server side code.Diffuse
Hello Quentin. I added two screenshots : "Collection type" and "Permission with POST api url". I hope it will help you to understand.Smackdab
you could be missing http in the URL and you can validate URL in browser or post man. axios.get('localhost:5000/api/data')Lawanda
I
2

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.

Ibby answered 19/5, 2022 at 16:18 Comment(6)
Thank you Zied. I just added "comment" because this is the object that received my datas. It didn't work either.Smackdab
No comment is an object. The API expects a string. Console log it first to see what's stored in it. I guess it has this shape { content: 'some text', pseudo: 'some other text' }. Or you can test by sending a static string just for test purposes. Otherwise if this does not work you need first to take a look into the API itself and maybe I would try it on Postman as well first !Ibby
Thank you. I replaced "comment" with "JSON.stringify(comment)" so that when I console log it, I have the string {"pseudo":"Test","content":"test"} displayed. But still I have the same error. I tested my API with Postman, and indeed, "data" is null and the "message" is Missing \"data\" payload in the request body. Should I change something with axios or is the problem somewhere else?Smackdab
So it doesn't work with Postman either ? You need to take a look what's the shape of payload that the API expect ? Does the API expect just a string ? Does it expect an object that has data in it like { data: 'your comment goes here' }Ibby
How do I find the type of shape of payload that my API expect ? I tested many solutions, I didn't find it yet. Here, you have the error sent with Postman forum.strapi.io/t/help-me-to-use-strapi-400-error/18769.Smackdab
Hello Zied Hf. The API expected an object that has a data. Thank you very much for your help !Smackdab
T
0

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.

Terrieterrier answered 21/6, 2022 at 15:37 Comment(0)
O
0

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

Ogham answered 21/6, 2022 at 16:0 Comment(0)
U
0

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));
Unreflecting answered 19/9, 2022 at 23:41 Comment(0)
C
0

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

Celia answered 13/7, 2023 at 18:33 Comment(0)
S
0

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

Stately answered 20/7, 2023 at 12:10 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Conifer

© 2022 - 2024 — McMap. All rights reserved.