天天看点

react 16 集成fetch 及 egg跨域处理

# 全局安装
npm install -g create-react-app
# 构建一个my-app的项目
npx create-react-app my-app
cd my-app

# 启动编译当前的React项目,并自动打开 http://localhost:3000/
npm start
           
fetch 集成

//方式一:安装fetch版本isomorphic-fetch
npm install isomorphic -fetch --save
import fetch from "isomorphic-fetch";

//方式二:安装 Fetch Polyfill的 whatwg-fetch脚本库,可以解决 fetch 的兼容性 
npm install --save whatwg-fetch 
import 'whatwg-fetch'      

使用whatwg-fetch

import 'whatwg-fetch'
import { requestUrl } from './requestconfig.js'
let request = {
    post: (info) => {
        var bodyvalue = "";
        var arr = [];
        for (var i in info.body) {
            bodyvalue += i + "=" + info.body[i] + "&";
        }
        bodyvalue = bodyvalue.slice(0, bodyvalue.length - 1);
        fetch(requestUrl + info.url, {
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: bodyvalue
        }).then(resp => {
            return resp.json()
        }).then((res) => {
            info.success(res);
        }).catch(function (e) {
            info.error(e);
        });
    },
    get: (info) => {
        fetch(requestUrl+info.url, {
            method: "GET",
            mode: "cors",
            headers: {
                "Content-Type": "application/json",
            },
            // body:JSON.stringify(info.body)
        }).then(resp=>{
            return resp.json()
        }).then((res)=>{
            info.success(res);
        }).catch(function (e) {
            info.error(e);
        })
    },
    delete: (info) => {
        fetch(requestUrl + info.url, {
            method: "DELETE",
            mode: "cors",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            // body:JSON.stringify(info.body)
        }).then(resp => {
            return resp.json()
        }).then((res) => {
            info.success(res);
        }).catch(function (e) {
            info.error(e);
        })
    },
    put: (info) => {
        let bodyvalue = "";
        let arr = [];
        for (let i in info.body) {
            bodyvalue += i + "=" + info.body[i] + "&";
        }
        bodyvalue = bodyvalue.slice(0, bodyvalue.length - 1);
        fetch(requestUrl + info.url, {
            method: "PUT",
            mode: "cors",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: bodyvalue
        }).then(resp => {
            return resp.json()
        }).then((res) => {
            info.success(res);
        }).catch(function (e) {
            info.error(e);
        });
    },
}

export default request
           

fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了流量的浪费 

Pomise.all的使用

Promise.all可以将多个Promise实例包装成一个新的Promise实例。同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回最先被reject失败状态的值。

Promise.race的使用

顾名思义,Promse.race就是赛跑的意思,意思就是说,Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。

/**
 * 让fetch也可以timeout
 *  timeout不是请求连接超时的含义,它表示请求的response时间,包括请求的连接、服务器处理及服务器响应回来的时间
 * fetch的timeout即使超时发生了,本次请求也不会被abort丢弃掉,它在后台仍然会发送到服务器端,只是本次请求的响应内容被丢弃而已
 * @param {Promise} fetch_promise    fetch请求返回的Promise
 * @param {number} [timeout=120000]   单位:毫秒,这里设置默认超时时间为10秒
 * @return 返回Promise
 */
import {fetch} from 'whatwg-fetch';
let queryString=require('querystring');
function timeout_fetch(fetch_promise,timeout = 120000) {
    let timeout_fn = null; 
 
    //这是一个可以被reject的promise
    let timeout_promise = new Promise(function(resolve, reject) {
        timeout_fn = function() {
            reject('timeout promise');
        };
    });
 
    //这里使用Promise.race,以最快 resolve 或 reject 的结果来传入后续绑定的回调
    let abortable_promise = Promise.race([
        fetch_promise,
        timeout_promise
    ]);
 
    setTimeout(function() {
        timeout_fn();
    }, timeout);
 
    return abortable_promise ;
}

let common_url = '/';  //服务器地址
let token = '';   
/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法:GET、POST,只能大写
 * @param {JSON} [params=''] body的请求参数,默认为空
 * @return 返回Promise
 */
export function fetchRequest(url, method="GET", params = ''){
    let header = {
        "Content-Type": "application/json;charset=UTF-8",
        "accesstoken":token  //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
    };
    // console.log('request url:',url,params);  //打印请求参数
    if(method === 'GET'){   //如果网络请求中带有参数
        let urlStr=common_url + url;
        if(params){
            urlStr=urlStr+"?"+queryString.stringify(params);
        }
        return new Promise(function (resolve, reject) {
            timeout_fetch(fetch(urlStr, {
                method: method,
                headers: header
            })).then((response) => response.json())
                .then((responseData) => {
                    // console.log('res:',url,responseData);  //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch( (err) => {
                    // console.log('err:',url, err);     //网络请求失败返回的数据        
                    reject(err);
                });
        });
    }else{   //如果网络请求中没有参数
        return new Promise(function (resolve, reject) {
            timeout_fetch(fetch(common_url + url, {
                method: method,
                headers: header,
                body:JSON.stringify(params)   //body参数,通常需要转换成字符串后服务器才能解析
            })).then((response) => response.json())
                .then((responseData) => {
                    //console.log('res:',url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch( (err) => {
                  //  console.log('err:',url, err);   //网络请求失败返回的数据  
                    reject(err);
                });
        });
    }
}
           

使用:

import {fetchRequest} from '../../utils/request';
export function getAeticle(obj){
   return fetchRequest('api/article/getarticle','GET',obj)
}

export function getArtinfo(obj){
   return fetchRequest('api/article/getartinfo','POST',obj);
}
           

eggjs解决跨域

1.安装egg-cors插件

npm i egg-cors --save //yarn add egg-cors
           

2.在/config/plugin.js中开启设置

module.exports = {
	//其它插件...
	cors: {
	  enable: true,
	  package: 'egg-cors'
	}
	//其它插件...
}
           

3.在/config/config.default.js中对其进行配置

config.cors = {
    origin: 'http://localhost:8080',//匹配规则  域名+端口  *则为全匹配
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
  };