webpack和vue-cli的devServer.proxy,vite的server.proxy配置记录

在学习前后端分离项目时,解决开发环境的跨域问题。 特此记录一下

基本用法

mmodule.exports = {
  devServer: {
    proxy: {
      '/sign': 'http://localhost:8081'
    }
  }
};

//当请求 /sign/xxx 就会被代理到 http://localhost:8081/sign/xxx, 
//例如 /sign/user 现在会被代理到请求 http://localhost:8081/sign/user

如果不希望传递/sign,则如下配置

mmodule.exports = {
  devServer: {
    proxy: {
      '/sign': {
          target: 'http://localhost:8081',
          pathRewrite: {'^/api',''}
      }
    }
  }
};

//当请求 /sign/xxx 就会被代理到 http://localhost:8081/xxx, 
//例如 /sign/user 现在会被代理到请求 http://localhost:8081/user

默认情况下,不接受HTTPS上运行且认证且证书无效的后端服务器。如果需要,设置secure:false

mmodule.exports = {
  devServer: {
    proxy: {
      '/sign': {
          target: 'http://localhost:8081',
          secure: false
      }
    }
  }
};

如果想将多个特定路径代理到同一个目标,则可以使用一个或多个带有context属性的对象的数组

module.exports = {
  devServer: {
    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'http://localhost:8081',
      },
    ],
  },
};

当进行代理时,Host 头部的源默认会保持原状;你可以设置 changeOrigin 为 true 来覆盖这种行为。

假如后端地址为http://localhost:3000,前端为http://localhost:3001,如果设置changeOrigin:true那么后端通过request.getHeader(“Host”)获取的地址将是http://localhost:3000

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      }
    }
  }
};

当没有设置changeOrigin时:

在这里插入图片描述

设置了changeOrigin:true

在这里插入图片描述

具体原因的话,我也是个小白。所以抱歉了我也不知道🥲

对于浏览器请求,你想要提供一个 HTML 页面,但是对于 API 请求则保持代理。可以通过请求头中的Accept属性来配置。

module.exports = {
 //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        bypass: function(req, res, proxyOptions) {
          if (req.headers.accept.indexOf('html') !== -1) {
            return '/edit.html';
          }
        }
      }
    }
  }  
};

上面代码中:如果请求头中的Accept属性中包含html则会转发到当前目录下的edit.html页面。

代理多个不同的路径

module.exports = {
    devServer: {
        proxy: {
            '/api/action': {
                target: 'http://192.191.1.3',
                changeOrigin: true,
                ws: true,
                secure: false
            },
            '/api': {
                target: 'http://192.191.1.2',
                changeOrigin: true,
                ws: true,
                secure: false
            },
        }
    }
};

注意:匹配多个的时候要将匹配范围最小的放在最前面。

vue-cli和vite配置和webpack的代理配置大致一样,但是vite的不是devServer.proxyserver.proxy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值