无法在'Window'无效模式下执行'fetch'

时间:2018-06-12 03:22:32

标签: 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        
  })
}

1 个答案:

答案 0 :(得分:2)

从标题中删除CORS模式。似乎您开始在JavaScript规范中使用Stage-0或Stage-2。在该规范中,出于某些原因,提取不允许使用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', ....