React配置proxy代理解决跨域问题

来源:程序思维浏览:5976次
在用react获取接口需要配置proxy代理,为什么要配置这个呢?是因为在实际开发当中为了安全性服务端给的接口不支持跨域,那么咱们在开发的时候如何解决跨域问题呢?那就需要配置proxy代理。

React配置proxy代理

使用creat-react-app构建的项目,前后端的接口联调,对于端口proxy设置、网络请求axios插件的使用以及fetch 插件的使用:

1、proxy设置

可以直接在package.json下配置,具体如下

方法一:"proxy": "域名"

方法二:
"proxy":{
    "/proxy": {
      "target": "http://vueshop.glbuys.com",
      "changeOrigin": true,
      "pathRewrite": {
        "^/proxy": ""
      }
    }
  }

2、axios插件的使用

使用npm下载插件

npm install axiso --save
axios的使用,其中header是默认application/json;charset=utf-8。

import React, { Component } from 'react';
import axios from 'axios';


class Test extends Component {
    constructor (props) {
        super(props)
    }

    getaxiosPost () {
        axios({
            method:'post',
            url:'/api/excel/web/list',
            data:{
                type:"import",
                page:1,
                pageSize:10
            },
            headers: {
                'Content-Type': 'application/json;charset=utf-8'
            }
        }).then(function(res){
           console.log(res.data);
        }).catch(function(error){
            console.log(error);
        });
    }

    getaxiosGet () {
        axios({
            method:'get',
            url:'/api/excel/web/status/disable/2',
            headers: {
                'Content-Type': 'application/json;charset=utf-8'
            }
        }).then(function(res){
            console.log(res.data);
        }).catch(function(error){
            console.log(error);
        });
    }

    render() {
        return (
            <div id="test-container">
                <p>search:{this.props.location.search} </p>
                <p>state:{this.props.location.state.mold} </p>
                <div onClick={this.getaxiosPost()}>axios的post请求</div>
                <div onClick={this.getaxiosGet()}>axios的get请求</div>
                <div onClick={() =>  this.props.history.goBack()}>返回上一页</div>
            </div>
        );
    }
}
export default Test;
3、fetch 插件的使用

     安装 whatwg-fetch、es6-promise

npm install whatwg-fetch es6-promise  --save
  fetch代码的封装:http.js

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

//将json对象拼接成 key=val&key=val 的字符串形式
function obj2params(obj) {
    var result = '';
    var item;
    for(item in obj){
        result += '&' + item + '=' +encodeURIComponent(obj[item]);
    }

    if(result) {
        result = result.slice(1);
    }
    return result;
}

export function postGpio(url,param) {
    var result = fetch(url, {
        method: 'post',
        mode:'cors',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: obj2params(param)
    });

    return result;
}

export function getGpio(url,param) {
    var result = fetch(url, {
        credentails: 'include',
        mode: "cors",
        header: {
            "Content-Type": "json"
        },
    });
    return result;
}
fetch使用,请求

import React, { Component } from 'react';
import {getGpio,postGpio} from "../http";


export default class Test extends Component {
    constructor (props) {
        super(props)
    }

    getFetchPost () {
        const result = postGpio('/api/excel/web/list',{
            type:"import",
            page:1,
            pageSize:10
        });

        result.then(res => {
            return res.json()
            console.log(res,19)
        }).then(json => {
            // get result
            const data = json
            console.log(data,22)
        }).catch(ex => {
            // 发生错误
            console.error('获取数据出错, ', ex.message)
        })
    }

    getFetchGet () {
        const result = getGpio('/api/excel/web/status/disable/2');

        result.then(res => {
            return res.json()
            console.log(res,19)
        }).then(json => {
            // get result
            const data = json
            console.log(data,22)
        }).catch(ex => {
            // 发生错误
            console.error('获取数据出错, ', ex.message)
        })
    }

    render() {
        return (
            <div id="test-container">
                <p>search:{this.props.location.search} </p>
                <p>state:{this.props.location.state.mold} </p>
                <div onClick={this.getFetchPost()}>axios的post请求</div>
                <div onClick={this.getFetchGet()}>axios的get请求</div>
                <div onClick={() =>  this.props.history.goBack()}>返回上一页</div>
            </div>
        );
    }
}

好了大家可以测试一下看看能不能跨域了。当然这个跨域必须在开发者环境使用,生产环境下不能跨域。
精品好课
HTML5基础入门视频教程易学必会
HTML5基础入门视频教程,教学思路清晰,简单易学必会。适合人群:创业者,只要会打字,对互联网编程感兴趣都可以学。课程概述:该课程主要讲解HTML(学习HTML5的必备基础语言)、CSS3、Javascript(学习...
React实战视频教程仿京东移动端电商
React是前端最火的框架之一,就业薪资很高,本课程教您如何快速学会React并应用到实战,对正在工作当中或打算学习React高薪就业的你来说,那么这门课程便是你手中的葵花宝典。
HTML5视频播放器video开发教程
适用人群1、有html基础2、有css基础3、有javascript基础课程概述手把手教你如何开发属于自己的HTML5视频播放器,利用mp4转成m3u8格式的视频,并在移动端和PC端进行播放支持m3u8直播格式,兼容...
VUE2+VUE3视频教程从入门到精通(全网最全的Vue课程)
VUE是目前最火的前端框架之一,就业薪资很高,本课程教您如何快速学会VUE+ES6并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己封装组件,正式上线白屏问题,性能优化等。对正在工作当中或打算学习VUE高薪就...
Vue2+Vue3+ES6+TS+Uni-app开发微信小程序从入门到实战视频教程
2021年最新Vue2+Vue3+ES6+TypeScript和uni-app开发微信小程序从入门到实战视频教程,本课程教你如何快速学会VUE和uni-app并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己...
最新完整React+VUE视频教程从入门到精,企业级实战项目
React和VUE是目前最火的前端框架,就业薪资很高,本课程教您如何快速学会React和VUE并应用到实战,教你如何解决内存泄漏,常用库的使用,自己封装组件,正式上线白屏问题,性能优化等。对正在工作当中或打算学习Re...
最新完整React视频教程从入门到精通纯干货纯实战
React是目前最火的前端框架,就业薪资很高,本课程教您如何快速学会React并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己封装组件,正式上线白屏问题,性能优化等。对正在工作当中或打算学习React高薪就...
jQuery视频教程从入门到精通
jquery视频教程从入门到精通,课程主要包含:jquery选择器、jquery事件、jquery文档操作、动画、Ajax、jquery插件的制作、jquery下拉无限加载插件的制作等等......
收藏
扫一扫关注我们