仓库案例
nodejs-proxy
创建项目目录
安装模块
1 2
| npm install --save-dev http-proxy-middleware npm install --save express
|
实现代码
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| const express = require('express'); const app = express(); var proxy = require('http-proxy-middleware');
var onProxyReq = function(proxyReq, req, res) { }
var onError = function(err, req, res) { console.log('Something went wrong.') console.log('And we are reporting a custom error message.') }
var options = { target: 'https://api.server.domain', rejectUnauthorized:false, changeOrigin: true, onProxyReq: onProxyReq, onError: onError, logLevel: "debug" };
var exampleProxy = proxy('/api/**',options); app.use(exampleProxy);
app.listen('3000', function() { console.log('[DEMO] Server: listening on port 3000') });
|
解释:
从前端访问localhost:3000,地址以/api/开始的所有请求转发到https://api.server.domain后端服务
例如:
localhost:3000/api/common/info => https://api.server.domain/api/common/info
运行服务