http-proxy-middleware
Advanced tools
Comparing version 0.0.5 to 0.1.0
34
index.js
var httpProxy = require('http-proxy'); | ||
var utils = require('./lib/utils'); | ||
var handlers = require('./lib/handlers'); | ||
@@ -7,17 +8,38 @@ var httpProxyMiddleware = function (context, opts) { | ||
var proxyOptions = opts || {}; | ||
// Legacy option.proxyHost | ||
// set options.headers.host when option.proxyHost is provided | ||
if (proxyOptions.proxyHost) { | ||
console.log('*************************************'); | ||
console.log('[HPM] Deprecated "option.proxyHost"'); | ||
console.log(' Use "option.headers.host" instead'); | ||
console.log(' "option.proxyHost" will be removed in future release.'); | ||
console.log('*************************************'); | ||
proxyOptions.headers = proxyOptions.headers || {}; | ||
proxyOptions.headers.host = proxyOptions.proxyHost; | ||
} | ||
// create proxy | ||
var proxy = httpProxy.createProxyServer(proxyOptions); | ||
console.log('[HPM] Proxy created:', context, proxyOptions.target); | ||
// handle option.pathRewrite | ||
if (proxyOptions.pathRewrite) { | ||
var pathRewriter = utils.createPathRewriter(proxyOptions.pathRewrite); | ||
if (proxyOptions.proxyHost) { | ||
proxy.on('proxyReq', utils.proxyReqHost); | ||
proxy.on('proxyReq', function (proxyReq, req, res, options) { | ||
handlers.proxyPathRewrite(proxyReq, pathRewriter); | ||
}); | ||
} | ||
// handle error and close connection properly | ||
proxy.on('error', function (err, req, res) { | ||
utils.proxyError(err, req, res, proxyOptions); | ||
handlers.proxyError(err, req, res, proxyOptions); | ||
}); | ||
return fnProxyMiddleWare; | ||
console.log('[HPM] Proxy created:', context, proxyOptions.target); | ||
function fnProxyMiddleWare (req, res, next) { | ||
return middleware; | ||
function middleware (req, res, next) { | ||
if (utils.hasContext(context, req.url)) { | ||
@@ -24,0 +46,0 @@ proxy.web(req, res); |
@@ -0,5 +1,57 @@ | ||
var url = require('url'); | ||
module.exports = { | ||
hasContext : require('./utils/has-context'), | ||
proxyReqHost : require('./utils/proxy-req-host'), | ||
proxyError : require('./utils/proxy-error') | ||
hasContext : hasContext, | ||
createPathRewriter : createPathRewriter | ||
} | ||
function hasContext (context, uri) { | ||
var urlPath = url.parse(uri).path; | ||
return urlPath.indexOf(context) === 0; | ||
} | ||
/** | ||
* Create rewrite function, to cache parsed rewrite rules. | ||
*/ | ||
function createPathRewriter (config) { | ||
var rules = parsePathRewriteRules(config); | ||
return rewritePath; | ||
function rewritePath (path) { | ||
var result = path; | ||
rules.forEach(function (rule) { | ||
if (rule.regex.test(path)) { | ||
result = result.replace(rule.regex, rule.value); | ||
} | ||
}); | ||
return result; | ||
} | ||
} | ||
function parsePathRewriteRules (config) { | ||
var rules = []; | ||
if (isObject(config) === false) { | ||
throw new Error('[HPM] Invalid pathRewrite config. Expecting an object literal with pathRewrite configuration'); | ||
} | ||
for (var key in config) { | ||
if (config.hasOwnProperty(key)) { | ||
rules.push({ | ||
regex : new RegExp(key), | ||
value : config[key] | ||
}); | ||
console.log('[HPM] Proxy rewrite rule created: "' + key + '" -> "' + config[key] + '"'); | ||
} | ||
} | ||
return rules; | ||
} | ||
function isObject (val) { | ||
return Object.prototype.toString.call(val) === '[object Object]' && typeof val === 'object'; | ||
} |
{ | ||
"name": "http-proxy-middleware", | ||
"version": "0.0.5", | ||
"description": "http-proxy middleware for connect", | ||
"version": "0.1.0", | ||
"description": "The one-liner http-proxy middleware", | ||
"main": "index.js", | ||
"scripts": { | ||
"test": "mocha --reporter spec", | ||
"cover": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && rm -rf coverage", | ||
"cover": "rm -rf coverage && istanbul cover ./node_modules/mocha/bin/_mocha", | ||
"coveralls": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && istanbul-coveralls && rm -rf coverage" | ||
@@ -21,4 +21,5 @@ }, | ||
"connect", | ||
"express", | ||
"browser-sync", | ||
"gulp-connect" | ||
"gulp" | ||
], | ||
@@ -32,11 +33,16 @@ "author": "Steven Chim", | ||
"devDependencies": { | ||
"chai": "^2.1.1", | ||
"browser-sync": "^2.7.13", | ||
"chai": "^3.0.0", | ||
"connect": "^3.4.0", | ||
"coveralls": "^2.11.2", | ||
"mocha": "^2.2.1", | ||
"express": "^4.13.1", | ||
"istanbul": "^0.3.17", | ||
"istanbul-coveralls": "^1.0.3", | ||
"mocha": "^2.2.5", | ||
"mocha-lcov-reporter": "0.0.2" | ||
}, | ||
"dependencies": { | ||
"http-proxy": "^1.9.0", | ||
"http-proxy": "^1.11.1", | ||
"url": "^0.10.3" | ||
} | ||
} |
141
README.md
# http-proxy-middleware | ||
[![Build Status](https://img.shields.io/travis/chimurai/http-proxy-middleware/master.svg?style=flat-square)](https://travis-ci.org/chimurai/http-proxy-middleware) | ||
[![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square)](https://coveralls.io/r/chimurai/http-proxy-middleware) | ||
[![dependency Status](https://img.shields.io/david/chimurai/http-proxy-middleware.svg?style=flat-square)](https://david-dm.org/chimurai/http-proxy-middleware#info=devDependencies) | ||
[![devDependency Status](https://img.shields.io/david/dev/chimurai/http-proxy-middleware.svg?style=flat-square)](https://david-dm.org/chimurai/http-proxy-middleware#info=devDependencies) | ||
[![NPM version](https://img.shields.io/npm/v/npm.svg?style=flat-square)](https://www.npmjs.com/package/http-proxy-middleware) | ||
[![MIT license](https://img.shields.io/npm/l/http-proxy-middleware.svg?style=flat-square)](https://www.npmjs.com/package/http-proxy-middleware) | ||
Middleware for [connect](https://github.com/senchalabs/connect) and [browser-sync](https://github.com/BrowserSync/browser-sync) | ||
The one-liner proxy middleware for [connect](https://github.com/senchalabs/connect), [express](https://github.com/strongloop/express) and [browser-sync](https://github.com/BrowserSync/browser-sync) | ||
@@ -15,86 +15,107 @@ ## Install | ||
## Usage | ||
## Core concept | ||
Create and configure the proxy middleware. | ||
```javascript | ||
var proxy = proxyMiddleware('/api', {target: 'http://www.example.org'}); | ||
// 'proxy' is now ready to be used in a server. | ||
### core concept | ||
Create and configure the proxy middleware so it can be used as middleware in connect or browser-sync. | ||
``` | ||
## Example | ||
```javascript | ||
// include dependencies | ||
var express = require('express'); | ||
var proxyMiddleware = require('http-proxy-middleware'); | ||
// configure proxy middleware | ||
var context = '/api'; // requests with this path will be proxied | ||
var options = { | ||
target: 'http://www.example.org', // target host | ||
changeOrigin: true // needed for virtual hosted sites | ||
}; | ||
// create the proxy | ||
var proxy = proxyMiddleware(context, options); | ||
// use the configured `proxy` in web server | ||
var app = express(); | ||
app.use(proxy); | ||
app.listen(3000); | ||
``` | ||
* `context` path to proxy. Example: '/api' | ||
* `options.target` target host to proxy to. (See "Options" for all options) | ||
* `options.target` target host to proxy to. (See "[Options](#options)" for all options) | ||
### connect | ||
Example: Proxy http://localhost:3000/ajax requests to http://cdnjs.cloudfare.com/ajax | ||
**Tip:** For [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based), you'll need to use the option `changeOrigin` and set it to `true`. | ||
```javascript | ||
var http = require('http'); | ||
var connect = require('connect'); | ||
var proxyMiddleware = require('http-proxy-middleware'); | ||
## Compatible servers: | ||
http-proxy-middleware is compatible with the following servers: | ||
* [connect](https://www.npmjs.com/package/connect) | ||
* [express](https://www.npmjs.com/package/express) | ||
* [browser-sync](https://www.npmjs.com/package/browser-sync) | ||
var context = '/ajax'; | ||
var proxy = proxyMiddleware(context, {target: 'http://cdnjs.cloudflare.com'}); | ||
var app = connect(); | ||
app.use(context, proxy); | ||
## Options | ||
http.createServer(app).listen(3000); | ||
``` | ||
* (DEPRECATED) **option.proxyHost**: Use `option.changeOrigin = true` instead. | ||
* **option.pathRewrite**: object, rewrite the url path. Object-keys will be used as _RegEx_ to match paths. | ||
### browser-sync | ||
Example: Proxy http://localhost:3000/ajax requests to http://cdnjs.cloudfare.com/ajax | ||
```javascript | ||
{ | ||
"^/old/api" : "/new/api", // rewrite path | ||
"^/remove/api" : "" // remove path | ||
} | ||
``` | ||
```javascript | ||
var browserSync = require('browser-sync'); | ||
var proxyMiddleware = require('http-proxy-middleware'); | ||
The following options are provided by the underlying [http-proxy](https://www.npmjs.com/package/http-proxy). | ||
* **option.target**: url string to be parsed with the url module | ||
* **option.forward**: url string to be parsed with the url module | ||
* **option.agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects) | ||
* **option.secure**: true/false, if you want to verify the SSL Certs | ||
* **option.xfwd**: true/false, adds x-forward headers | ||
* **option.toProxy**: passes the absolute URL as the `path` (useful for proxying to proxies) | ||
* **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects. | ||
var proxy = proxyMiddleware('/ajax', {target: 'http://cdnjs.cloudflare.com'}); | ||
Undocumented options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy/blob/master/lib/http-proxy.js#L32). | ||
* **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}` | ||
* **option.changeOrigin**: true/false, adds host to request header. | ||
* **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path> | ||
* **option.ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request> | ||
* **option.localAddress** : Local interface string to bind for outgoing connections | ||
* **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header. | ||
* **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false. | ||
* **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null. | ||
browserSync({ | ||
server: { | ||
baseDir: "./", | ||
port: 3000, | ||
middleware: [proxy] | ||
} | ||
}); | ||
``` | ||
### gulp + browser-sync | ||
Example: Proxy http://localhost:3000/ajax requests to http://cdnjs.cloudfare.com/ajax | ||
```javascript | ||
var gulp = require('gulp'); | ||
var browserSync = require('browser-sync'); | ||
var proxyMiddleware = require('http-proxy-middleware'); | ||
## More Examples | ||
gulp.task('serve', function () { | ||
var proxy = proxyMiddleware('/ajax', {target: 'http://cdnjs.cloudflare.com'}); | ||
To [view the examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples), clone the http-proxy-middleware repo and install the dependencies: | ||
browserSync({ | ||
server: { | ||
baseDir: "./", | ||
port: 3000, | ||
middleware: [proxy] | ||
} | ||
}); | ||
}); | ||
```bash | ||
$ git clone https://github.com/chimurai/http-proxy-middleware.git | ||
$ cd http-proxy-middleware | ||
$ npm install | ||
``` | ||
gulp.task('default', ['serve']); | ||
Then run whichever example you want: | ||
```bash | ||
$ node examples/connect | ||
``` | ||
## Options | ||
Or just [explore the examples sources](https://github.com/chimurai/http-proxy-middleware/tree/master/examples): | ||
* `examples/connect` - Example usage with [connect](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect) | ||
* `examples/express` - Example usage with [express](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express) | ||
* `examples/browser-sync` - Example usage with [browser-sync](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync) | ||
* **option.proxyHost**: true/false, proxy `host` header to target. default:false. Useful for [Name-based virtual hosting](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based) | ||
## Tests | ||
### http-proxy options: | ||
These options are provided by the underlying [http-proxy](https://www.npmjs.com/package/http-proxy). | ||
* **target**: url string to be parsed with the url module | ||
* **forward**: url string to be parsed with the url module | ||
* **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects) | ||
* **secure**: true/false, if you want to verify the SSL Certs | ||
* **xfwd**: true/false, adds x-forward headers | ||
* **toProxy**: passes the absolute URL as the `path` (useful for proxying to proxies) | ||
* **hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects. | ||
To run the test suite, first install the dependencies, then run `npm test`: | ||
```bash | ||
$ npm test | ||
``` | ||
## License: | ||
@@ -101,0 +122,0 @@ The MIT License (MIT) |
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
24876
381
143
9
4
Updatedhttp-proxy@^1.11.1