react 用fetch跨域请求,看控制台,是成功拿到数据,但是程序里返回的确是error

我是用dva框架,用fetch跨域请求。是成功拿到数据,但是程序里返回的确是error,不知错在哪里,望指教

1.看了下控制台,是成功拿到数据。如图:

clipboard.png

打印了下返回结果,返回的确是error,如图:

clipboard.png

2.代码如下:

import fetch from 'dva/fetch';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options,transform) {

const headers= {
    'Accept': 'application/x-www-form-urlencoded',
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
    'Access-Control-Allow-Credentials': true
};
const parmas=Object.assign(headers,options,{credentials: 'include'});
  return fetch(url,parmas)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      
      if(transform instanceof Function){
        return transform(data);
      }

      return data;
    })
}

3.发起请求的地方:

effects: {
    *queryUser ({payload}, {call, put}) {
      const data = yield call(Services.userInfo, parse(payload));
      console.log(data);
      if (data.success) {
      
      }else{
      
      }
        
}
阅读 7.4k
3 个回答

fetch 的 问题 是因为 代理配置出错了,proxy要与env同级

{
  "entry": "src/index.js",
  "env": {
    "development": {
      "extraBabelPlugins": [
        "dva-hmr",
        "transform-runtime",
        ["import",{"libraryName":"antd","style":"css"}]
      ]
    },
    "production": {
      "extraBabelPlugins": [
        "transform-runtime",
        ["import",{"libraryName":"antd","style":"css"}]
      ]
    }

  },
  "proxy": {
        "/baomuWeb": {
          "target": "http://需要代理的域名/",
          "changeOrigin": true
        }

    }
}

fetch 部分只需要加上 (credentials: 'include'允许带上cookie),其他没什么特别

const parmas = {
    ...options,
    credentials: 'include'
  };
  return fetch(url,parmas)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      data.success=data.result==='success';
      if(transform instanceof Function){
        return transform(data);
      }

      return data;
    })
    .catch(err => ({ err }));
'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
    'Access-Control-Allow-Credentials': true

这些头是服务端返回的,不是请求头,先删掉这个在测试下

开发环境需要配置proxy,将跨域的地址代理出去。
eg:

proxy: {
    '/api/**': {
      'target': 'http://192.168.204.37:8080/'
    },
}

生产环境也需要配置proxy。如nginx的配置,通过pass_proxy代理出去。

location /api {
    pass_proxy http://xxx.xxx.xx.xx/xxx;
}
推荐问题