javascript - 无法在“窗口”无效模式下执行“获取”
问题描述
突然之间,我在浏览器中的所有 fetch 请求都抛出了Failed to execute 'fetch' on 'Window' invalid mode
. 他们以前工作得很好。任何人都可以对此提供提示吗?我的代码如下:
function request(params) {
let { api, method, data } = params
let localParm = {
method: method,
mode: { mode: 'no-cors' },
credentials: 'include',
headers: typeof Headers !== 'undefined' ? new Headers({ 'content-type': 'application/x-www-form-urlencoded' }) : { 'content-type': 'application/x-www-form-urlencoded' }
}
let url = apiNames[api] || api
if (method == "POST") {
localParm.body = toQueryString(data)
} else if (method == "GET") {
if (data) {
url += ("?" + toQueryString(data || {}))
}
}
const reqFunc = method === 'jsonp' ? fetchJsonp : fetch;
return reqFunc(url, localParm).then((response) => {
if (response.status === 200 || response.ok === true) {
try {
return response.json()
}catch(e){
console.log('11')
}
} else {
console.log('22')
}
}).then((res) => {
return res
})
}
解决方案
从标题中删除 CORS 模式。似乎您开始在 JavaScript 规范中使用 stage-0 或 stage-2。在该规范中,由于某种原因 fetch 不允许 CORS 模式。
let localParm = {
method: method,
mode: { mode: 'no-cors' },
credentials: 'include',
headers: typeof Headers !== 'undefined' ? new Headers({ 'content-type': 'application/x-www-form-urlencoded' }) : { 'content-type': 'application/x-www-form-urlencoded' }
}
应该看起来像
let localParm = {
method: method,
credentials: 'include', ....
推荐阅读
- r - 在 Plotly 中显示 3d 轴,R
- discord.js - 我需要在 discord.js 中停止循环的示例
- java - TextToSpeech android API 22不播放音频
- android - 使用 Retrofit 方法调用 delete Yii2 被覆盖
- java - 如何在 Spring Boot 应用程序中启用 HTTPS,在 Tomcat 中部署为 WAR 文件?
- python - 尝试用 cvxpy 解决数独
- android - CardView 的圆角半径在 Google Maps InfoWindow 中表现异常
- typescript - 在 TypeScript 中为导入的符号指定显式类型
- vba - VBA 搜索和替换脚本会产生很长的延迟
- javascript - js构建加载div