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

这篇博客介绍了如何在React应用中利用Fetch API发送跨域POST请求。通过设置'Content-Type'为'application/x-www-form-urlencoded',并配置mode为'cors',实现了与服务器的交互。同时,提到了fetch-npm-node.js文件的内容,用于处理以'//'开头的URL,并全局替换fetch相关对象。
摘要由CSDN通过智能技术生成
  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;
}
有不懂的地方欢迎沟通!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值