【发布时间】:2017-02-04 20:40:45
【问题描述】:
我正在开发我的第一个基于 React 的前端应用程序。此应用程序的目的是连接到 RESTful API 以获取和发布数据。问题是我无法发送令牌标头以通过安全检查,因此请求失败。
我得到不同的错误取决于我使用的浏览器。
这是我的 main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import promise from 'es6-promise';
import 'isomorphic-fetch';
promise.polyfill();
class Employee extends React.Component {
constructor(props){
super(props);
this.state = {employees : []};
}
componentWillMount(){
fetch('http://localhost:8080/app/rest/employees',{ method: 'get', headers: {'Access-Control-Allow-Origin': 'http://localhost:8080', 'Content-Type': 'x-www-form-urlencoded', 'token' : '93edf459ba78d13be0e9d21143238f43796de1f6ebbc58b133af7f33b8222676'}})
.then((response) => {
return response.json();
})
.then((downscalings) => {
this.setState({ employees: values });
})
}
update(){
this.setState({name : 'John'});
}
render(){
return <div>
<input type="text" value="aaaa"></input>
<button onClick={this.update}>Set name</button>
</div>
}
}
ReactDOM.render(
<Employee/>,
document.getElementById('container')
);
这是来自浏览器的输出日志错误:
Failed to load resource: the server responded with a status of 401 (No Autorizado)
index.html:1 Fetch API cannot load http://localhost:8080/app/rest/employees. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.html:1 Uncaught (in promise) TypeError: Failed to fetch(…)
这是网络跟踪:
获取员工
本地主机:8080
0 乙
OPTIONS 员工
401 未授权
本地主机:8080
37 乙
我假设没有发送标头,因此 REST 服务拒绝该请求。由于警告,我还添加了 CORS 标头。我做错了什么?
【问题讨论】:
-
后端需要token的方式
-
能否请您显示浏览器记录的网络调用的请求标头和响应标头?
-
@Aatif Bandey 后端从标头“token”中获取令牌。我认为它隐含在我展示的代码中。
-
您在网络选项卡中看到的我的意思是方法是
OPTIONS或POST -
Access-Control-Allow-Origin是在您的 OPTIONS 请求之后发送的响应标头。您应该配置后端服务器 CORS 以允许来自前端的请求。你用什么后端?
标签: reactjs cors es6-promise