gpt4 book ai didi

javascript - Reactjs通过axios POST请求

转载 作者:行者123 更新时间:2023-11-28 14:43:36 25 4
gpt4 key购买 nike

您好,我正在尝试通过 axios 发送 ReactJS POST 请求,但出现错误,我浏览了所有文档,但错误尚未解决。

这是我的错误:

未捕获( promise 中)错误:请求失败,状态代码为 400 在 createError 处(在 (bundle.js:4621), :15:15 处评估) 结算时(在 (bundle.js:4615), :18:12 进行评估) 在 XMLHttpRequest.handleLoad(在 (bundle.js:4609), :77:7 处评估)

这是我的 Reactjs 代码:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
margin: 15,
marginLeft: 600
};
export default class Register extends React.Component {
constructor(props) {
super(props);
this.onSubmit=this.handleSubmit.bind(this);
}


handleSubmit(e) {
e.preventDefault();
var self = this;
var data = new FormData();
const payload = {
id: 111,
studentName: 'param',
age: 24,
emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

axios('http://localhost:8083/students',{
method: 'POST',
body: data,
headers: {
// 'Authorization': `bearer ${token}`,
'Content-Type': 'application/json'
}
})
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body);
});
}

render() {
return (
<form onSubmit={this.onSubmit}>
<div style={style}>
<TextField ref='id'
hintText="Enter Student id"
floatingLabelText="id"
/>
<br/>
<TextField ref='sname'
hintText="Enter your Last Name"
floatingLabelText="StudentName"
/>
<br/>
<TextField ref='age'
hintText="Enter your Age"
floatingLabelText="age"
/>
<br/>

<TextField ref='emailId'
hintText="Enter your Email"
floatingLabelText="emailId"
/>
<br/>
<br/>
<input type="submit" />


</div>
</form>


);
}


}

最佳答案

检查axios api发出 POST 请求的正确方法是:

const payload = {
id: 111,
studentName: 'param',
age: 24,
emailId: 2
}

axios({
method: 'post',
url: '/user/12345',
data: payload, // you are sending body instead
headers: {
// 'Authorization': `bearer ${token}`,
'Content-Type': 'application/json'
},
})

关于javascript - Reactjs通过axios POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47260216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com