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

来源:互联网 发布:二叉树的python实现 编辑:程序博客网 时间:2024/05/21 10:47
  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;
}
有不懂的地方欢迎沟通!

原创粉丝点击