- 0
- 11 浏览
使用http-proxy-middleware
结合Express
来开发一个网关,示例代码如下:
安装依赖
npm install express http-proxy-middleware
创建服务器
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const PORT = process.env.PORT || 8080;
// // 全局中间件,为所有请求添加默认请求头
app.use((req, res, next) => {
req.headers['X-API-GATEWAY'] = 'NODE-1.0';
next();
});
// 代理 /api/app-api
app.use(
'/api/app-api',
createProxyMiddleware({
target: 'http://app-service:4000',
changeOrigin: true,
pathRewrite: {
'^/': '/api/app-api/',
},
on: {
proxyReq: (proxyReq, req, res) => {
// 添加自定义请求头
// proxyReq.setHeader('X-APP-PACKAGE-NAME', 'werq.asdf');
console.log('onProxyReq called for /api/app-api');
console.log('Headers being sent to target:', proxyReq.getHeaders());
},
},
})
);
// 代理 /api/products 到 http://products-service:4000
app.use(
'/api/products',
createProxyMiddleware({
target: 'http://products-service:4000',
changeOrigin: true,
pathRewrite: {
'^/api/products': '', // 重写路径,去掉 /api/products 前缀
},
})
);
// 启动服务器
app.listen(PORT, () => {
console.log(`API Gateway running on port ${PORT}`);
});
启动服务
node filename.js
代码:https://github.com/lifengdi/node-api-gateway
除非注明,否则均为风笛原创文章,转载必须以链接形式标明本文链接
本文链接:https://www.lifd.site/tech/shi-yong-httpproxymiddleware-he-express-gou-jian-api-wang-guan/
“觉得文章还不错?微信扫一扫,赏作者一杯咖啡吧~”
分类
登录
0 评论
最旧