我正在使用reactjs和axios创建一个index.html。它来自我的apache localhost。
我在Chrome浏览器中打开了链接Response for preflight has invalid HTTP status code 400
。我使用chrome中的插件启用了CORS。
当我尝试使用twitter api的axios时,我得到:
var url = 'https://api.twitter.com/1.1/search/tweets.json';
axios({
url: url,
method:'get',
q:'twitterapi',
json:'true',
headers: {
"Authorization": "Bearer "+this.state.bearer_token,
'Content-Type' : 'application/json'
}
})
.then(function(response) {
this.setState(prevState => ({
get_json: response
})
)
})
.catch(function(error){
console.log(error);
});
以下是axios的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Twitter API</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Module extends React.Component {
constructor(props) {
super(props);
this.state = {
bearer_token:"&&&&&&&&&&&&&***************++++++++++++++++++++++++++++",
get_json:""
}
this.handleClickGetJSON = this.handleClickGetJSON.bind(this)
}
handleClickGetJSON(){
var url = 'https://api.twitter.com/1.1/search/tweets.json';
axios({
url: url,
method:'get',
q:'twitterapi',
headers: {
"Authorization": "Bearer "+this.state.bearer_token,
'Content-Type' : 'application/json'
}
})
.then(function(response) {
this.setState(prevState => ({
get_json: response
})
)
})
.catch(function(error){
console.log(error);
});
}
render() {
return (
<div>
<p>{ this.state.bearer_token }</p>
<p>{ this.state.get_json }</p>
<button onClick={this.handleClickGetJSON}>GetBearerToken</button>
</div>
);
}
}
ReactDOM.render(
<Module />,
document.getElementById('root')
);
</script>
</body>
</html>
index.html的完整代码如下
Date | ID | Value
--------------------
2/4/17 | 3 | 4.4
2/4/17 | 9 | 6.2
2/9/17 | 3 | 4.7
2/9/17 | 4 | 7.4
2/9/17 | 9 | 9.4
2/11/17 | 3 | 9.7
2/11/17 | 7 | 12.4
答案 0 :(得分:1)
对于预检请求,您应该有以下两个标题:
这些请求标头要求服务器提供实际请求的权限。您的预检响应需要确认这些标题,以便实际请求起作用。
对于跨域调用,浏览器通常在实际调用之前进行OPTIONS调用。您的服务器基本上需要允许该方法。