nginx
1. 配置本地磁盘映射
location ^~ /project/ {
alias D:/git/project/;
}
适用于在本地部署静态工程,将 alias
的值指向打包文件的磁盘目录,注意路径要使用反斜杠 “/” ,然后就可以通过 http://127.0.0.1/project/
访问了。
2. 配置服务器代理
- 场景一:
接口:http://127.0.0.1:8000/user/list
请求:/api/user/list
location ^~ /api/ {
proxy_pass http://127.0.0.1:8000/;
}
- 场景二
接口:http://127.0.0.1:8000/api/user/list
请求:/api/user/list
location ^~ /api/ {
proxy_pass http://127.0.0.1:8000; # 注意末尾没有斜杠
}
- 场景三
接口:http://127.0.0.1:8000/passport/user/list
请求:/api/user/list
location ^~ /api/ {
proxy_pass http://127.0.0.1:8000/passport/;
}
webpack
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8000', // 值为 'ip+端口' 或 '域名'
pathRewrite: { '^/api': '' }, // 自定义前缀需要重写
// ws: true, // 适用于 websocket
// changeOrigin: true, // 默认为 false,请求头 Host 指向本地,如果为 true,Host 指向 target
}
}
}
}
各类脚手架
本质上都是基于 webpack 的代理配置
1. @angular/cli
首先项目根目录创建 proxy.config.json
{
"/api": {
"target": "http://127.0.0.1:8000",
"pathRewrite": {
"^/api": ""
}
}
}
启动服务时指定代理文件
ng serve --proxy-config proxy.config.json
2. create-react-app
脚手架版本低于2.0时,在 package.json
中配置 "proxy" 值
{
"proxy": {
"/api/**": {
"target": "http://127.0.0.1:8000",
"changeOrigin": true
}
}
}
2.0版本以后,"proxy" 只支持配置字符串,就是只能配置一个代理
{
"proxy": "http://127.0.0.1:8000"
}
如果要配置多个代理,可以使用 http-proxy-middleware 中间件
npm i http-proxy-middleware -S
// 或者
yarn add http-proxy-middleware
然后在 src 目录下创建如下 setupProxy.js
,并写入下方代码,创建这个文件之后重启项目会自动引用
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
proxy('/api', {
target: 'http://127.0.0.1:8000',
changeOrigin: true
})
);
app.use(
proxy('/passport', {
target: 'http://127.0.0.1:8080',
changeOrigin: true
})
);
// app.use(...)
}
3. umi
在 config/config.ts
或 .umirc.ts
中修改
export default {
// ...
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
pathRewrite: {
// '^/api': '',
},
}
}
}
4. @vue/cli
配置 vue.config.js 中 devServer.proxy
,同 webpack