天天看點

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'
  };