IE11中使用fetch API发起外部POST请求出现SCRIPT7002权限拒绝错误求助
解决IE11中Fetch POST请求的"Access is denied"错误
首先得明确核心问题:IE11完全不支持原生的Fetch API,你遇到的错误大概率是兼容性问题叠加跨域(CORS)、Basic Auth处理限制导致的。下面给你一步步的解决方案:
1. 补上Fetch和Promise的Polyfill
IE11既不支持Fetch,也不支持Promise,必须先引入对应的polyfill才能让代码跑起来:
- 安装依赖:
npm install whatwg-fetch es6-promise --save - 在项目入口文件(比如
index.js)顶部引入:import 'es6-promise/auto'; import 'whatwg-fetch';
2. 检查服务器端CORS配置
错误码0x80070005通常和跨域权限相关,确保服务器正确设置了这些响应头:
Access-Control-Allow-Origin:如果请求带凭证(比如Cookie),不能设为*,要指定具体域名(如http://localhost:你的端口号)Access-Control-Allow-Headers: Authorization:因为你的请求携带了Authorization头,必须显式允许Access-Control-Allow-Credentials: true:如果需要传递凭证,必须开启这个配置
3. 替换为原生XMLHttpRequest实现(更可靠)
即使加了polyfill,Fetch在IE11里处理认证头仍可能有问题,直接用IE11原生支持的XHR实现会更稳定:
export const signIn = (email, password) => { // 处理非ASCII字符的base64编码(IE11的btoa不支持非ASCII) const utf8AuthStr = unescape(encodeURIComponent(`${email}:${password}`)); const base64 = btoa(utf8AuthStr); return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', '你的接口URL', true); xhr.setRequestHeader('Authorization', `Basic ${base64}`); xhr.setRequestHeader('Content-Type', 'application/json'); // 根据接口需求调整 xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { try { const response = JSON.parse(xhr.responseText); resolve(response); } catch (e) { reject(new Error('响应解析失败')); } } else { reject(new Error(`请求失败,状态码:${xhr.status}`)); } }; xhr.onerror = function() { reject(new Error('网络请求错误')); }; // 发送请求体(如果需要的话,根据接口要求调整) xhr.send(JSON.stringify({})); }); };
4. 排查Basic Auth的替代方案
如果以上方法仍无效,可以尝试把认证信息直接嵌入URL(安全性稍弱,但可用于排查问题):
const encodedEmail = encodeURIComponent(email); const encodedPassword = encodeURIComponent(password); const authUrl = `https://${encodedEmail}:${encodedPassword}@你的接口域名/接口路径`; // 用XHR请求这个authUrl即可
内容的提问来源于stack exchange,提问作者Matheus Lima
相关产品推荐
相关产品推荐

