react配置多个代理,跨域

配置一个或者多个代理的问题

在项目中可能遇到跨域问题就需要配置代理 那问题来了 怎么配置呢 在哪里配置呢 今天就讨论一下这个问题 emmm重点来了

配置跨域的有两个地方可以配置

  • 修改package.json文件

    配置一个

         "name": "wangguan",
         "version": "0.1.0",
         "private": true,
         "proxy":"http://172.19.5.35:9536",
    

    配置多个

        "name": "wangguan",
        "version": "0.1.0",
         "private": true,
         "proxy":{
           "/api": {
               "target": "http://172.19.5.35:9536",
               "ws": true
             },
         "/apc": {
               "target": "http://179.19.5.35:9536",
               "ws": true
             }
     },
    

    配置多个是个对象尽然报错 哈哈 ? !!!!在最新的create-react-app v2升级版(webpack4.0)中,如果proxy不是字符串,并不能这么在 package.json直接配置,会报错!
    解决方案
    通过查阅create-react-app的官方文档https://facebook.github.io/create-react-app/docs/getting-started,找到了如下的解决方案

    安装http-proxy-middleware管理包,cnpm http-proxy-middleware --save
    在项目目录src/下新建setupProxy.js文件,然后写入如下代码:

      const proxy = require(‘http-proxy-middleware‘);
    	module.exports = function(app) {
    	  app.use(proxy(/api‘, { 
    	       target: ‘http://192.168.1.144:8181,
    	       secure: false,
    	       changeOrigin: true,
    	       pathRewrite: {
    	        "^/api": "/"
    	       },
    	       // cookieDomainRewrite: "http://localhost:3000"
    	    }));
    	};
    

    官方文档在这里
    链接:Proxying API Requests in Development

    安装http-proxy-middleware
    官方文档内容

    Note: this feature is available with react-scripts@2.0.0 and higher.

    If the proxy option is not flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware.
    You can use this feature in conjunction with the proxy property in package.json, but it is recommended you consolidate all of your logic into src/setupProxy.js.

    First, install http-proxy-middleware using npm or Yarn:

        $ npm install http-proxy-middleware --save
    	$ # or
    	$ yarn add http-proxy-middleware
    

    Next, create src/setupProxy.js and place the following contents in it:

        const proxy = require('http-proxy-middleware');
    
    	module.exports = function(app) {
    	  // ...
    	};
    

    You can now register proxies as you wish! Here’s an example using the above http-proxy-middleware:

       const proxy = require('http-proxy-middleware');
    
    	module.exports = function(app) {
    	  app.use(proxy('/api', { target: 'http://localhost:5000/' }));
    	};
    

    我的设置请求 代码src/setupProxy.js

     const proxy = require('http-proxy-middleware');
    
    module.exports = function(app) {
      // ...You can now register proxies as you wish!
      app.use(proxy('/api', { 
        target: 'http://172.19.5.35:9536',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
         "^/api": "/"
        },
       }));
       app.use(proxy('/apc', { 
        target: 'http://172.19.5.34:9531',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
         "^/apc": "/"
        },
       }));
      //app.use(proxy('/apc', { target: 'http://172.19.5.34:9531' }));
    }
    

    相关代码
    axios拦截设置
    request.js文件

   import axios from 'axios'
   import {Toast} from 'antd-mobile';  

//创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 200000, // 请求超时时间
  withCredentials: true // 选项表明了是否是跨域请求
})
service.interceptors.request.use(config => {
  Toast.loading('加载中',1)              // loading组件,显示文字加载中,自动关闭延时1s
  console.log('request go');
  return config;
}, err => {
  console.log('请求失败')
  return Promise.reject(err)
})
//拦截响应
service.interceptors.response.use(config => {
  Toast.hide()                             // 销毁Toast组件
  console.log('response get')
  return config;
}, err => {
  console.log('响应失败')
  return Promise.reject(err)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * code为非000000是抛错 可结合自己业务进行修改
    */
    const res = response.data
    if (res.code !== '000000') {
      console.log("response",res)
      res.code = res.data.code
       res.message = res.response.data.msg
      Toast.info(res.code+res.message, 2);
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)
export default service

批量接口
src/axios/pay.js

import fetch from '../utils/request'
// 1根据订单id获取订单信息
export function getOrderById( data) {
  return fetch({
   // baseURL:"http://172.19.5.34:9531",
   // url: '/getOrderById',
    url: '/apc/getOrderById',
    method: 'post',
    data,
  })
}
// 2.获取商户支持的支付方式
export function queryByOwenerIdAndOwnerType( params) {
  return fetch({
    url: '/api/productSubscribe/queryByOwenerIdAndOwnerType',
    method: 'get',
    params,
  })
}

页面调用

 import React, { Component } from 'react';
 import {List ,Radio,Button} from 'antd-mobile';
 import './payChoose.less';
// using ES6 modules
 import { BrowserRouter, Route, Link } from 'react-router-dom'
 import {getOrderById,queryByOwenerIdAndOwnerType} from '../../axios/pay'

 const Item = List.Item;
 const Brief = Item.Brief;
 const RadioItem = Radio.RadioItem;


class pay  extends Component {
  state={
    amount:0,
    coursewareName:''
  }
  requestList = ()=>{
   console.log("requestList")
   let data ={
    "orderId":"527850648009699328"
  }
   getOrderById(data).then(res=>{
     console.log("res=",res)
     const data  =  res.data
     console.log("data=",data)
     if(res.data){
      this.setState({
          amount:data.amount,
          coursewareName:data.coursewareName
      },()=>{
          
      })
// 第二个接口
      let ownerId =data.ownerId
      let ownerType =data.ownerType
      let params={
        ownerId:ownerId,
        ownerType:ownerType
      }
      queryByOwenerIdAndOwnerType(params).then(res=>{
        if(res.data){
          let data = res.data.data
        }
      })
     }
     console.log("data=",data)
   }).catch(error=>{
     console.log("error",error)
   })


  }

  componentDidMount(){
    this.requestList();
  }
  render() {
    return (
     
  );
  }
}

export default pay;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值