在我的 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)
});
Run Code Online (Sandbox Code Playgroud)
但是我收到了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
Run Code Online (Sandbox Code Playgroud)
尝试使用 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)
});
Run Code Online (Sandbox Code Playgroud)