Reputation: 6612
In my React.js app I use the jquery .ajax
method to retrieve info from a backend API. To do this I need to add a authorization token as a header and I added the headers
option:
$.ajax({
url: this.props.source,
headers: { 'Accept':'application/json', 'Authorization':'Token 36d417' },
dataType: 'jsonp',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
But I receive a 401 Unauthorized
response from the server. When I check the headers they don't seem to be added?
Remote Address:189.28.154.73:8080
Request URL:https://todos-api.com/api/v1/todos?callback=jQuery1100005772984796203673_1424179650018&_=1424179650019
Request Method:GET
Status Code:401 Unauthorized
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6,nl;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Host:todos-api.com
Pragma:no-cache
Referer:https://todos-reactjs.io/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
Upvotes: 4
Views: 3796
Reputation: 13560
Try using the beforeSend callback
$.ajax({
url: this.props.source,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', 'Token 36d417');
xhr.setRequestHeader('Accept', 'application/json');
},
dataType: 'jsonp',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
Upvotes: 5