【发布时间】:2018-09-06 22:00:18
【问题描述】:
我有一个使用 reactjs 和 axios 制作的 index.html。它是从我的 apache localhost 提供的。
我正在我的 chrome 浏览器中打开链接 http://localhost/~user/index.html。我已经使用 chrome 中的插件启用了 CORS。
当我尝试将 axios 与 twitter api 一起使用时,我得到:
Response for preflight has invalid HTTP status code 400
下面是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);
});
index.html的完整代码如下
<!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>
【问题讨论】:
标签: reactjs google-chrome cors twitter-oauth axios