Axioserror:状态代码400的请求失败(在React JS中)

发布于 2025-01-30 19:37:38 字数 2310 浏览 4 评论 0 原文

我正在尝试使用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: {…},请求:xmlhttprequest, …}

这是我的代码:

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

commentapi.js文件:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

世俗缘 2025-02-06 19:37:38

您不会向API发送任何内容。 commentapi.create(您在此处评论)

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

在您的服务器中,您需要返回有用的错误消息。就像“嘿,没有消息,请在有效载荷中发送消息”。这将帮助您更好地了解发生的事情。

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.

愿与i 2025-02-06 19:37:38

对于面临同一问题的任何其他人,如果您从机构发送具有列表的数据,请尝试更改您的GET HTTP请求发布。
希望这会有所帮助。

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.

屋顶上的小猫咪 2025-02-06 19:37:38

如果您收到400(),这意味着该确定收到了您的请求,但内容无效。阅读API的文档,以确保您发送正确的有效载荷。

默认情况下,如果Axios收到了2xx以外的其他东西,它将引发异常

,如果您要

console.log(data)

工作,请不要忘记添加等待

await console.log(data)

以便代码在等待服务器的答案试图console.log()

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

浅唱ヾ落雨殇 2025-02-06 19:37:38

您的问题在这里...

  json.stringify(comment)
 

这将字符串传递给Axios,它将将其解释为 text/plain ,然后将请求 content-type 标题设置为相同。

您的API很有可能期望 application/json application/x-www-form-urlencoded 请求正文,并拒绝纯文本。

要发送前者,只需省略 json.stringify(),让Axios处理序列化和内容类型检测

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

可以使用 urlsearchParams 来实现后者。

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

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));
陪你到最终 2025-02-06 19:37:38

就我而言,我没有在包装中提及(代理)。

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

我们只是彼此的过ke 2025-02-06 19:37:38

有时,当您克隆git存储库时,则需要在React和后端中安装所有所需的依赖项,如果需要,但是如果在Frontend发出Axios请求时会产生错误,请尝试Byrunning此命令

NPM安装Axioio

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文