问题描述
有必要写一个XMLHttpRequest Web API的拦截器,我已经写到这个阶段了
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 策略。