• React脚手架配置axios代理 (1.配置在package.json, 2.配置在setupProxy.js)


    1:给项目安装axios

    npm install axios
    

    2:导入axios工具包

    import axios from 'axios';

    React脚手架添加中间代理实现跨域(方法一)

    配置单个代理

    在项目的package.json文件中添加:

    "proxy":"http://localhost:5000/"

    使用的地方直接使用

    1. import axios from 'axios';
    2. click = () => {
    3. axios.get('http://localhost:3000/ctiy').then(
    4. response => {
    5. console.log('获取数据成功',response.data)
    6. },
    7. error => {
    8. console.log('获取数据失败',error)
    9. }
    10. )
    11. }

    React脚手架添加中间代理实现跨域(方法二 :setupProxy.js)

    配置多个代理

    1. 在src文件中添加setupProxy.js文件 ,无需单独应用,webpack会自动引入文件。 
    2. setupProxy.js中写的是common.js语法
    3. setupProxy.js中的文件内容

    react17版本的代理配置需要在src/setupProxy.js中配置

     

    1. setupProxy.js内容
    2. const proxy = require('http-proxy-middleware');
    3. module.exports = function(app) {
    4. app.use(
    5. proxy('/api11', {
    6. target: "http://localhost:5000",
    7. //target配置成'http://localhost:5000'意味着只要发现/api11前缀的请求,
    8. //就自动转发到'http://localhost:5000'这个地址,
    9. //并且通过配置pathRewrite: {'^/api11': ''}把添加了/api11的请求地址还原回去
    10. changeOrigin: true,
    11. // 控制服务器收到的请求头中的Host的值 如果设置为true,服务器不会知道真实的请求地址,
    12. //只会知道代理的地址,如果设置为false,服务器会知道真正请求的地址
    13. pathRewrite: {'^/api11': ''}
    14. // 重写请求路径 这个必须要加,如果不加 服务器端收到的请求地址是 /api/url 请求地址就不对了
    15. }),
    16. proxy('/banzhuan', {
    17. target: "http://localhost:5001",
    18. changeOrigin: true,
    19. pathRewrite: {'^/banzhuan': ''}
    20. })
    21. )
    22. }

     

    react18版本的配置,主要的差异是需要用http-proxy-middleware中的createProxyMiddleware创建代理

     

    1. setupProxy.js内容
    2. const {createProxyMiddleware} = require('http-proxy-middleware');
    3. module.exports = function (App) {
    4. App.use(
    5. createProxyMiddleware('/api11', {
    6. target: 'http://localhost:5000',
    7. changeOrigin: true,
    8. pathRewrite:{'^/api11':''}
    9. }
    10. ),
    11. createProxyMiddleware('/banzhuan', {
    12. target: 'http://localhost:5001',
    13. changeOrigin: true,
    14. pathRewrite:{'^/banzhuan':''}
    15. }
    16. )
    17. )
    18. }

    页面使用

    1. 使用页面内容
    2. click = () => {
    3. axios.get('http://localhost:3000/api11/ctiy').then(
    4. response => { console.log('请求成功', response) },
    5. error => {console.log('请求失败,',error)}
    6. )
    7. }
    8. clickCase = () => {
    9. axios.get('http://localhost:3000/banzhuan/cars').then(
    10. response => { console.log('小汽车请求成功', response) },
    11. error =>{console.log('失败',error)}
    12. )
    13. }

  • 相关阅读:
    分享 8 个 VSCode 插件,提升你的编码体验
    中国机构票房排行查询易语言代码
    RocketMQ如何保证消息被有序消费
    小Z的拼数游戏c++(求 解)
    FPGA中的LUT查找表工作原理。
    R语言时间序列数据算术运算:使用diff函数计算时间序列数据的逐次差分、使用时间序列之间的除法计算相对变化率(乘以100获得百分比)
    论文阅读 (77):Abductive Learning with Ground Knowledge Base
    为什么需要Code Review?
    我的创作纪念日
    09_一种比较高效的记忆方法
  • 原文地址:https://blog.csdn.net/zqlbanzhuan/article/details/127936740