http-proxy-middleware接口转发

安装

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

使用

//Proxy `/api` requests to `http://www.example.org`
var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();
app.use('/api', proxy({target: 'http://www.example.org', changeOrigin: true}));
app.listen(3000);

概念

Proxy middleware configuration.

proxy([context,] config)

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

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

// 'apiProxy' is now ready to be used as middleware in a server.
  • context: Determine which requests should be proxied to the target host.
    (more on context matching)
  • options.target: target host to proxy to. (protocol + host)

高级

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

// proxy middleware options
var 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)
var exampleProxy = proxy(options);

// mount `exampleProxy` in web server
var app = express();
    app.use('/api', exampleProxy);
    app.listen(3000);

你可能感兴趣的:(http-proxy-middleware接口转发)