express反向代理中间件http-proxy-middleware

http-proxy-middleware用于把请求代理转发到其他服务器的中间件。

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use('/api', proxy({
    target: 'http://localhost:4000/', 
    changeOrigin: true
}));
app.listen(3000);

在3000端口启动了http服务,利用了app.use('/api', proxy({target: 'http://localhost:4000/', changeOrigin: true})),请求localhost:3000/api,被转发到4000端口,相当于请求http://localhost:4000/api。 

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use('/api', proxy({
    target: 'https://www.baidu.com', 
    changeOrigin: true,
    pathRewrite: {
        '^/api' : '',
        '^/api/old-path' : '/api/new-path', // 重写请求,请求api/old-path,会被解析为/api/new-path
        '^/api/remove/path' : '/path'
    }
}));
app.listen(3000);

在浏览器地址栏输入“localhost:3000/api”,就会跳转到“https://www.baidu.com

var express = require('express');
var proxy = require('http-proxy-middleware');


// 使用代理
var app = express();
app.use('/api', proxy({
    target: 'https://www.zcool.com.cn',
    changeOrigin: true,
    ws: true,// 是否代理websockets
    pathRewrite: {
        '^/api' : ''
    },
    router: {
        // 如果请求主机 == 'dev.localhost:3000',
        // 重写目标服务器 'https://www.zcool.com.cn' 为 'https://www.baidu.com'
        'dev.localhost:3000' : 'https://www.baidu.com'
    }
}));
app.listen(3000);

浏览器地址栏输入localhost:3000/api,会跳转到https://www.zcool.com.cn

浏览器地址栏输入dev.localhost:3000/api,会跳转到https://www.baidu.com

发布了46 篇原创文章 · 获赞 23 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43586120/article/details/100117160