react -搭建服务

import 'whatwg-fetch';
import 'es6-promise';
require('es6-promise').polyfill();
import * as common from 'common/common.js';

function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.text();
} else {
common.toast("请求错误");
common.closeLoading();
var error = new Error(response.statusText);
error.response = response;
throw error;
}
}

function parseJSON(response) {
var result = JSON.parse(response);
if(result.code == "99"){
common.closeLoading();
common.gotoLogin();
}
return result;
}

// 发送 get 请求
export function get(url) {
url = common.urlTransmit(url);
var headers = {
'Accept': 'application/json',
'Content-Type' : 'application/json'
}
if(common.tvToken()){
headers.tvToken = common.tvToken()
}
let requestConfig = {
credentials: 'include',
method: "GET",
headers: headers
}
return fetch(url, requestConfig).then(checkStatus).then(parseJSON);
}

// 发送 post 请求
export function post(url, paramsObj) {
url = common.urlTransmit(url);
var headers = {
'Accept': 'application/json, text/plain, /',
'Content-Type': 'application/x-www-form-urlencoded'
}
if(common.tvToken()){
headers.tvToken = common.tvToken()
}
return fetch(url, {
method: 'POST',
credentials: 'include',
headers: headers,
body: obj2params(paramsObj)
}).then(checkStatus).then(parseJSON);
}

// 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
function obj2params(obj) {
var result = '';
var item;
for (item in obj) {
result += '&' + item + '=' + encodeURIComponent(obj[item]);
}

if (result) {
    result = result.slice(1);
}

return result;

}

猜你喜欢

转载自www.cnblogs.com/pp-air/p/12084079.html