React 采用Fetch方式发送跨域POST请求

  1. 主实现类:
    import fetch from ‘isomorphic-fetch’;

export default async function post(url,method,params) {
//Content-Type: ‘application/json’
let response = await fetch(url,{method: method,headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
}, body: JSON.stringify(params),mode:”cors”});
let data;
if (response.status >= 200 && response.status < 300) {
data = await response.json();
}else{
data = {“retCode”:false,”retMesg”:”服务器异常(“+response.status+”)”};
}
alert(JSON.stringify(data.data)+”1111”);
//e(data);
return data;
}

  1. fetch-npm-node.js中的内容:
    “use strict”;

var realFetch = require(‘node-fetch’);
module.exports = function(url, options) {
if (/^\/\//.test(url)) {
url = ‘https:’ + url;
}
return realFetch.call(this, url, options);
};

if (!global.fetch) {
global.fetch = module.exports;
global.Response = realFetch.Response;
global.Headers = realFetch.Headers;
global.Request = realFetch.Request;
}
有不懂的地方欢迎沟通!

你可能感兴趣的:(java,post,fetch,react)