react中fetch的跨域使用

本文详细介绍了在React中使用fetch进行跨域数据请求的方法,包括fetch的介绍、安装、引入、暴露函数、get方式获取数据,以及如何通过设置CORS解决跨域问题。同时,还讲解了利用express发布模拟数据并配置允许跨域访问的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react中fetch的跨域使用


一、 fetch介绍
mock.js模拟数据(可以用express代替),fetch接收数据。

二、 安装fetch
Npm install whatwg-fetch –save
为了支持老版本的还需要安装es6-promise
Npm install es6-promise –save
这里写图片描述
三、 fecth的引入。
① 先建立一个fetch的文件夹。
这里写图片描述
② 在文件夹下创建test.js,并且在test.js中引入fetch

import 'whatwg-fetch'
import 'es6-promise'

四、 暴露函数,在外部引用函数
① 暴露

export  function getData() {
     }

② 外部引入函数(引入函数用大括号包裹,引入组件不需要)

import {getData} from "./fetch/test";
getData();

五、 fetch的get方式获取数据

export  function getData() {
    fetch('http://localhost:8000/api/1', {
        method: "GET",
        mode: "cors",
        headers:{
                    'Accept':'application/json,text/plain,*/*'
                }

    }).then(response => response.text())
        .then(result => {
            // 在此处写获取数据之后的处理逻辑
            console.log(result);
        }).catch(function (e) {
        console.log("fetch fail");
    });
    fetch('http://localhost:8000/api/2', {
        method: "GET",
        mode: "cors",
        headers:{
            'Accept':'application/json,text/plain,*/*'
        }

    }).then(response => response.json())
        .then(result => {
            // 在此处写获取数据之后的处理逻辑
            console.log(result);
        }).catch(function (e) {
        console.log("fetch fail");
    });

六、 用express发布模拟数据

var express = require('express');
var app = express();
var key={
    a:5,
    c:6
}
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials','true');
    next();
};
app.use(allowCrossDomain);
app.get('/api/1', function (req, res) {
    res.send('Hello World!');
});
app.get('/api/2', function (req, res) {
    res.type('application/json')
    res.send(key);
});
app.listen(8000, function () {
    console.log('Example app listening on port 8000!');
});

七、 跨域访问数据
React项目发布时会占用3000端口,所以模拟数据无法发布到3000端口,比如8000端口,但是需要在3000端口访问8000端口的数据,这时候就需要跨域访问
① 在fetch中声明cors
这里写图片描述
② 在express端允许cors跨域访问,并指明允许访问的ip地址。
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值