在我的React.js应用程序中,我使用jquery .ajax
方法从后端API检索信息。为此,我需要添加一个授权令牌作为标题,我添加了headers
选项:
$.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)
});
但我从服务器收到401 Unauthorized
响应。当我检查标题时,它们似乎不会被添加?
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
答案 0 :(得分:4)
尝试使用beforeSend回调
$.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)
});