首页 > 解决方案 > 无法在“窗口”无效模式下执行“获取”

问题描述

突然之间,我在浏览器中的所有 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        
  })
}

标签: javascriptfetch

解决方案


从标题中删除 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', ....

推荐阅读