【发布时间】:2018-04-25 19:27:00
【问题描述】:
您好,我正在尝试通过 fetch 进行 reactjs POST 请求,但出现两个错误,我浏览了所有文档但错误未解决。
错误:
- 无法加载 http://localhost:8083/students:预检响应包含无效的 HTTP 状态代码 403
- 未捕获(承诺中)类型错误:无法获取
这是我的 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));
fetch('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>
);
}
}
即使在这里我的表单值也是硬编码的。
【问题讨论】:
-
代码 403 表示禁止,请检查您的 API 的授权
-
我看到您的授权标头令牌已被注释掉。如果这不包括在内,您将得到 403,因为获取不会被授权
标签: javascript java reactjs rest fetch