【问题标题】:data not passed from frontend to REST API数据未从前端传递到 REST API
【发布时间】:2021-09-13 13:48:26
【问题描述】:

这是我的 React JS 代码:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            person: {
                id: 0,
                name: "name",
                email: "email"
            }
        }
    }
        
    handleChange = (event) =>{
        const  {name, value} = event.target;
        //setting the state
        this.setState({person: { ...this.state.person, [name]: value }});
    }
    
    handleFormSubmission = (event) =>{
        event.preventDefault();
    }
    
    
    someFunction = () =>{
        let apiCall;
        let personState = JSON.stringify(this.state.person);

        apiCall = await axios.put(`http://localhost:8000/api/people/update/${this.state.person.id}/`, {personState}, {headers:{token: this.props.token}});

    }
    
    
    render() {
        return (
            <form id="parent-container" onSubmit={this.handleFormSubmission}>
                <input type=text" value={this.state.person.name} name="personName" onChange={this.handleChange}
                <input type=text" value={this.state.person.name} name="personName" onChange={this.handleChange}
                
                <button type="submit" onClick={() => this.someFunction()}>Submit</button>
            </form>
        );
    }

}
export default App;

在谷歌浏览器中检查请求,这是我发现的:

标题:

General:

Request URL: http://localhost:8000/api/people/update/0/
Request Method: PUT
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin

Response Headers:

Access-Control-Allow-Origin: http://localhost:3000
Allow: PUT, PATCH, OPTIONS
Content-Length: 598
Content-Type: application/json
Date: Fri, 10 Sep 2021 23:08:55 GMT
Server: WSGIServer/0.2 CPython/3.8.1
Vary: Accept, Cookie, Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

Request Headers:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Accesstoken: someAccessToken
Connection: keep-alive
Content-Length: 503
Content-Type: application/json;charset=UTF-8
Host: localhost:8000
Origin: http://localhost:3000
Referer: http://localhost:3000/
sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
sec-ch-ua-mobile: ?1
sec-ch-ua-platform: "Android"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Mobile Safari/537.36

Request Payload:
person: "{\"id\":6,\"name\":\"some person\",\"email\":\"aaa@email.com\"}"

响应标签:

{
    "name":["This field is required."],
    "email":["This field is required."],
}

端点:

PUT http://localhost:8000/api/persons/update/6/ 400(错误请求)

从我上面看到的是,它没有使用 Axios PUT 请求将数据从前端传递到 REST API。 即使在使用 Postman 发送数据并发出 api 请求时它也可以工作。 这只发生在 PUT 和 POST 请求中,但 GET 请求可以正常工作。

有什么问题,为什么它没有在 Axios 请求中将数据从 React 发送到 REST API?

【问题讨论】:

  • 省略JSON.stringify()并直接发送状态是否有效:await axios.put('myurl', this.state.person, {headers...})

标签: javascript reactjs react-redux react-hooks react-router


【解决方案1】:

您将状态设置为

this.setState({person: { ...this.state.person, [name]: value }});

这使您的name 成为状态键。

例如,如果用户输入john 作为名称,您的状态将是:

{
  john: 'something i don't know',
  email: 'sth'
}

在此处阅读更多信息Computed property names

将此行改为

this.setState({person: { ...this.state.person, name: value }});

【讨论】:

    【解决方案2】:

    所以问题是我正在将一个对象传递给 Axios 请求的 data 参数, 它不应包含在对象的花括号 {} 中。

    在axios中应该是这样传递的:

    apiCall = await axios.put(`http://localhost:8000/api/people/update/${this.state.person.id}/`, this.state.person, {headers:{token: this.props.token}});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多