I am having an index.html made using reactjs and axios. Its being served from my apache localhost.
I am opening the link http://localhost/~user/index.html
in my chrome browser. I have enabled CORS using a plugin in chrome.
When i try to use axios with twitter api I get:
Response for preflight has invalid HTTP status code 400
The below is the code for 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);
});
The full code of index.html is as follows
<!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>