http-middle-proxy代理

it2022-05-05  211

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)

Context matching

path matching

proxy({…}) - matches any path, all requests will be proxied. proxy(’/’, {…}) - matches any path, all requests will be proxied. proxy(’/api’, {…}) - matches paths starting with /api multiple path matching

proxy(['/api', '/ajax', '/someotherpath'], {...}) wildcard path matching

proxy(’’, {…}) matches any path, all requests will be proxied. proxy(’/.html’, {…}) matches any path which ends with .html proxy(’/.html’, {…}) matches paths directly under path-absolute proxy(’/api//*.html’, {…}) matches requests ending with .html in the path of /api proxy([’/api/’, ‘/ajax/’], {…}) combine multiple patterns proxy([’/api/’, ‘!**/bad.json’], {…}) exclusion

Note: In multiple path matching, you cannot use string paths and wildcard paths together.

Router

option.router:对象/函数,重新定位特定请求的option.target。 // Use `host` and/or `path` to match requests. First match will be used. // The order of the configuration matters. router: { 'integration.localhost:3000' : 'http://localhost:8001', // host only 'staging.localhost:3000' : 'http://localhost:8002', // host only 'localhost:3000/api' : 'http://localhost:8003', // host + path '/rest' : 'http://localhost:8004' // path only } // Custom router function router: function(req) { return 'http://localhost:8004'; }

custom matching

/** * @return {Boolean} */ var filter = function(pathname, req) { return pathname.match('^/api') && req.method === 'GET' } var apiProxy = proxy(filter, { target: 'http://www.example.org' })

最新回复(0)