闽公网安备 35020302035485号
前言
我们在平常本地开发时,可能经常需要与后端进行联调,或者调用一些api,但是由于浏览器跨域的限制、开发与生产环境的差异、http与https等问题经常让联调的过程不够顺畅。所以本文介绍一下webpack的devServer中的proxy配置项。接下来让我们先看一下这个配置项的基本使用:
proxy: {
'/api': 'http://localhost:3000',
}
// 示例
// 假设你本地的前端服务跑在8080端口
axios.get('/api/user/info') // 会被转发到 -> localhost:3000/api/user/info
axios.get('/user/info') // 不会被转发, localhost:8080/user/info
2.路径重写:如果你不希望在代理请求时传递原始路径(例如/api),可以使用pathRewrite来重写它。这里的^/api: ''的意思是匹配接口路径中的/api,并将其替换为空字符串。proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: { '^/api': '' },
},
}
3.处理HTTPS和无效证书:默认情况下,代理不会接受运行在HTTPS上且证书无效的后端服务器。要允许这样的配置,可以将secure选项设置为false。proxy: {
'/api': {
target: 'https://other-server.example.com',
secure: false,
},
}
4.条件代理:通过一个函数判断是否需要代理。例如,对于浏览器请求,你可能希望提供一个HTML页面,而对于API请求,则希望代理它。proxy: {
'/api': {
target: 'http://localhost:3000',
bypass: function (req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
},
},
}
多路径代理:如果你想将多个特定路径代理到同一个目标,可以使用具有context属性的对象数组。proxy: [
{
context: ['/auth', '/api'],
target: 'http://localhost:3000',
},
]
改变原始主机头:代理默认保持原始的主机头。如果需要,可以通过设置changeOrigin为true来改变这个行为。proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
},
}
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// 入口文件配置
entry: './src/index.js',
// 输出文件配置
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
// 堆代码 duidaima.com
// 开发服务器配置
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
proxy: {
// 配置代理规则 '/api'
'/api': {
target: 'http://localhost:3000', // 目标服务器地址
pathRewrite: { '^/api': '' }, // 路径重写,将 '/api' 替换为 ''
secure: false, // 如果是 https 接口,需要配置为 true
changeOrigin: true // 需要虚拟托管站点
},
// 你可以在这里继续添加更多的代理规则
}
},
// 插件配置
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
// 模块配置
module: {
rules: [
// 在这里添加 loader
]
}
};
在这个配置中: