我正在使用axios进行React-Redux应用程序来进行REST调用。我正在尝试将一个令牌注入.NET REST API的Authorization标头,以用于验证调用。我已经尝试了多种方式来发送标题,但它们似乎都没有工作。我甚至尝试过没有运气的东西。我可以看到HTTPRequestMessage对象的“Access-Control-Allow-Headers”属性中列出的标头,但无法查看或访问该值。当我使用Postman发送它时,Authorization标头设置正确。这是React代码:
function callApi(endpoint, authenticated, data) {
let token = localStorage.getItem('id_token') || null;
const api = axios.create({method: 'POST', headers: {'Access-Token': `${token}`, 'Authorization': `${token}`, 'Content-Type': 'application/x-www-form-urlencoded'}});
//return fetch(BASE_URL + endpoint, config)
return api.post(BASE_URL + endpoint, config)
.then(response =>
response.text()
.then(data => ({ data, response }))
).then(({ data, response }) => {
if (!response.ok) {
return Promise.reject(data);
}
return data;
}).catch(err => console.log(err));
}
这是.NET控制台,您可以在其中看到Authorization标头为null:
request.Headers
{Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US, en; q=0.8, de; q=0.6
Host: localhost:3001
Referer: http://localhost:8080/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Access-Control-Request-Method: POST
Origin: http://localhost:8080
Access-Control-Request-Headers: access-token, authorization
}
Accept: {*/*}
AcceptCharset: {}
AcceptEncoding: {gzip, deflate, sdch, br}
AcceptLanguage: {en-US, en; q=0.8, de; q=0.6}
Authorization: null
CacheControl: null
Connection: {keep-alive}
ConnectionClose: null
Date: null
Expect: {}
ExpectContinue: null
From: null
Host: "localhost:3001"
IfMatch: {}
IfModifiedSince: null
IfNoneMatch: {}
IfRange: null
IfUnmodifiedSince: null
MaxForwards: null
Pragma: {}
ProxyAuthorization: null
Range: null
Referrer: {http://localhost:8080/}
TE: {}
Trailer: {}
TransferEncoding: {}
TransferEncodingChunked: null
Upgrade: {}
UserAgent: {Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36}
Via: {}
Warning: {}
这里是我在web.config中的CORS条目:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Authorization, X-Custom-Header, Access-Token" />
<add name="Access-Control-Expose-Headers" value="Content-Type, Authorization, X-Custom-Header, Access-Token" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
感谢您查看!