react中fetch的跨域使用

react中fetch的跨域使用


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

二、 安装fetch
Npm install whatwg-fetch –save
为了支持老版本的还需要安装es6-promise
Npm install es6-promise –save
react中fetch的跨域使用_第1张图片
三、 fecth的引入。
① 先建立一个fetch的文件夹。
react中fetch的跨域使用_第2张图片
② 在文件夹下创建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
react中fetch的跨域使用_第3张图片
② 在express端允许cors跨域访问,并指明允许访问的ip地址。
react中fetch的跨域使用_第4张图片

你可能感兴趣的:(前端-react)