利用webpack,vite 等工具配置代理
webapck
以vue项目为例
vue.config.js
module.exports = {
devServer: {
port: '8081', // 设置端口号
proxy: {
'/api': {
target: 'http://ahbcht.com', //API服务器的地址
changeOrigin: true, // 是否跨域,虚拟的站点需要更管origin
pathRewrite: {
'^/api': '',
}
}
},
}
}
vite
以vue项目为例
vite.config.ts
import { defineConfig } from "vite";
export default defineConfig({
server: {
proxy: {
"/api": {
target: "http://www.lingchen.kim:8888",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
});
nginx
http {
server {
listen 8081;
server_name localhost 127.0.0.1 10.20.11.153; # 站点域名
location /api {
proxy_pass http://10.20.11.153:1026;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
node
以express 和相关插件 express-http-proxy 为例
- 安装依赖
yarn add express-http-proxy
- 拦截相关代码
var proxy = require("express-http-proxy");
//配置项目多个接口代理,第一个匹配成功后,就不会继续执行
const proxyList = [
{
url: "/api",
target: "http://139.155.253.86:5000",
},
{
url: "/local",
target: "http://shenji.zlketang.com",
},
];
function proxyInit(app) {
proxyList.forEach(({ url, target }) => {
// 自动将头删除,设置改写也没用
app.use(
url,
proxy(target, {
limit: "5mb", // 限制大小
timeout: 5000, // 设置超时
// https: true, // 开启https
})
);
});
}
module.exports = proxyInit;
- 全局导入
// 代理
const proxy = require("./proxy/index");
proxy(app);