Javascript 通过XMLHttpRequest Web API添加身份验证头
有必要为XMLHttpRequestWebAPI编写一个拦截器,我已经编写到这个阶段了Javascript 通过XMLHttpRequest Web API添加身份验证头,javascript,typescript,xmlhttprequest,Javascript,Typescript,Xmlhttprequest,有必要为XMLHttpRequestWebAPI编写一个拦截器,我已经编写到这个阶段了 const { serverUrl, bearerToken } = this.config; const XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function ( method: string, url: string ) {
const { serverUrl, bearerToken } = this.config;
const XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function (
method: string,
url: string
) {
if (url.match(new RegExp(`^${serverUrl}`)) !== null && bearerToken) {
this.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.OPENED) {
this.setRequestHeader(
'Authorization',
`Bearer ${bearerToken}`
);
}
};
}
return XMLHttpRequestOpen.apply(this, arguments);
};
不幸的是,即使在开发人员控制台中看到身份验证头,我仍然收到401服务器响应
我错过了什么?承载令牌是100%正确的,因此我的实现有问题。由于我的解决方案是100%正确的,问题在于代理上的CORS策略。如果它显示在请求头中,则可能是服务器错误,而不是前端错误。