http-proxy-middleware_http-proxy-middleware的安装与使用

安装

npm install --save-dev http-proxy-middleware

代理中间件配置

createProxyMiddleware([context,] config)

const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
//                                    \____/   \_____________________________/
//                                      |                    |
//                                    context             options

// 'apiProxy' is now ready to be used as middleware in a server.
  • createProxyMiddleware([代理路径],{target:[目标路径]})
  • context:确定应将哪些请求代理到目标主机。
  • options.target: 要代理到的目标主机。(协议+主机)

示例

// include dependencies
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

// proxy middleware options
/** @type {import('http-proxy-middleware/dist/types').Options} */
const options = {
  target: 'http://www.example.org', // target host
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // proxy websockets
  pathRewrite: {
    '^/api/old-path': '/api/new-path', // rewrite path
    '^/api/remove/path': '/path', // remove base path
  },
  router: {
    // when request.headers.host == 'dev.localhost:3000',
    // override target 'http://www.example.org' to 'http://localhost:8000'
    'dev.localhost:3000': 'http://localhost:8000',
  },
};

// create the proxy (without context)
const exampleProxy = createProxyMiddleware(options);

// mount `exampleProxy` in web server
const app = express();
app.use('/api', exampleProxy);
app.listen(3000);
posted @ 2023-09-14 01:21  Syinho  阅读(830)  评论(0编辑  收藏  举报