node-http-proxy
는 웹소켓을 지원하는 HTTP 프로그래밍 가능 프록시 라이브러리입니다. 역방향 프록시, 로드 밸런서 등의 구성 요소를 구현하는 데 적합합니다.
npm install http-proxy --save
맨 위로 돌아가기
여기를 클릭하세요
맨 위로 돌아가기
createProxyServer
호출하고 options
객체를 인수로 전달하여 새 프록시가 생성됩니다(유효한 속성은 여기에서 사용 가능).
var httpProxy = require ( 'http-proxy' ) ;
var proxy = httpProxy . createProxyServer ( options ) ; // See (†)
†객체에서 Listen(..)이 호출되지 않는 한 웹 서버가 생성되지 않습니다. 아래를 참조하세요.
객체는 네 가지 메서드로 반환됩니다.
req, res, [options]
(일반 HTTP(S) 요청을 프록시하는 데 사용됨)req, socket, head, [options]
(WS(S) 요청 프록시에 사용됨)port
(귀하의 편의를 위해 웹 서버에서 개체를 래핑하는 기능)[callback]
(내부 웹서버를 닫고 특정 포트에서 수신 대기를 중지하는 함수)그런 다음 이러한 함수를 호출하여 요청을 프록시하는 것이 가능합니다.
http . createServer ( function ( req , res ) {
proxy . web ( req , res , { target : 'http://mytarget.com:8080' } ) ;
} ) ;
Event Emitter API를 사용하여 오류를 수신할 수 있습니다.
proxy . on ( 'error' , function ( e ) {
...
} ) ;
또는 콜백 API를 사용하여
proxy . web ( req , res , { target : 'http://mytarget.com:8080' } , function ( e ) { ... } ) ;
요청이 프록시되면 req
및 res
객체 모두에 변환을 적용하는 두 개의 서로 다른 파이프라인(여기에서 사용 가능)을 따릅니다. 첫 번째 파이프라인(수신)은 클라이언트를 대상에 연결하는 스트림의 생성 및 조작을 담당합니다. 두 번째 파이프라인(송신)은 대상에서 클라이언트로 데이터를 반환하는 스트림의 생성 및 조작을 담당합니다.
맨 위로 돌아가기
var http = require ( 'http' ) ,
httpProxy = require ( 'http-proxy' ) ;
//
// Create your proxy server and set the target in the options.
//
httpProxy . createProxyServer ( { target : 'http://localhost:9000' } ) . listen ( 8000 ) ; // See (†)
//
// Create your target server
//
http . createServer ( function ( req , res ) {
res . writeHead ( 200 , { 'Content-Type' : 'text/plain' } ) ;
res . write ( 'request successfully proxied!' + 'n' + JSON . stringify ( req . headers , true , 2 ) ) ;
res . end ( ) ;
} ) . listen ( 9000 ) ;
†listening(..)을 호출하면 웹 서버 생성이 트리거됩니다. 그렇지 않으면 프록시 인스턴스만 생성됩니다.
맨 위로 돌아가기
이 예에서는 자체 HTTP 서버를 사용하여 요청을 프록시하는 방법과 요청을 처리하기 위한 자체 논리를 넣을 수 있는 방법을 보여줍니다.
var http = require ( 'http' ) ,
httpProxy = require ( 'http-proxy' ) ;
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy . createProxyServer ( { } ) ;
//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http . createServer ( function ( req , res ) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy . web ( req , res , { target : 'http://127.0.0.1:5050' } ) ;
} ) ;
console . log ( "listening on port 5050" )
server . listen ( 5050 ) ;
맨 위로 돌아가기
이 예에서는 특수 헤더를 추가하여 나가는 프록시 요청을 수정하는 자체 HTTP 서버를 사용하여 요청을 프록시할 수 있는 방법을 보여줍니다.
var http = require ( 'http' ) ,
httpProxy = require ( 'http-proxy' ) ;
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy . createProxyServer ( { } ) ;
// To modify the proxy connection before data is sent, you can listen
// for the 'proxyReq' event. When the event is fired, you will receive
// the following arguments:
// (http.ClientRequest proxyReq, http.IncomingMessage req,
// http.ServerResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
//
proxy . on ( 'proxyReq' , function ( proxyReq , req , res , options ) {
proxyReq . setHeader ( 'X-Special-Proxy-Header' , 'foobar' ) ;
} ) ;
var server = http . createServer ( function ( req , res ) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy . web ( req , res , {
target : 'http://127.0.0.1:5050'
} ) ;
} ) ;
console . log ( "listening on port 5050" )
server . listen ( 5050 ) ;
맨 위로 돌아가기
때로는 원래 서버로부터 HTML/XML 문서를 받았을 때 이를 전달하기 전에 수정하고 싶을 때가 있습니다.
Harmon을 사용하면 프록시에 대한 부담을 최소한으로 유지하기 위해 스트리밍 스타일로 이 작업을 수행할 수 있습니다.
맨 위로 돌아가기
var http = require ( 'http' ) ,
httpProxy = require ( 'http-proxy' ) ;
//
// Create a proxy server with latency
//
var proxy = httpProxy . createProxyServer ( ) ;
//
// Create your server that makes an operation that waits a while
// and then proxies the request
//
http . createServer ( function ( req , res ) {
// This simulates an operation that takes 500ms to execute
setTimeout ( function ( ) {
proxy . web ( req , res , {
target : 'http://localhost:9008'
} ) ;
} , 500 ) ;
} ) . listen ( 8008 ) ;
//
// Create your target server
//
http . createServer ( function ( req , res ) {
res . writeHead ( 200 , { 'Content-Type' : 'text/plain' } ) ;
res . write ( 'request successfully proxied to: ' + req . url + 'n' + JSON . stringify ( req . headers , true , 2 ) ) ;
res . end ( ) ;
} ) . listen ( 9008 ) ;
맨 위로 돌아가기
대상 연결에 대한 보안 SSL 인증서의 유효성 검사를 활성화할 수 있습니다(자체 서명된 인증서는 피함). 옵션에서 secure: true
설정하기만 하면 됩니다.
//
// Create the HTTPS proxy server in front of a HTTP server
//
httpProxy . createServer ( {
target : {
host : 'localhost' ,
port : 9009
} ,
ssl : {
key : fs . readFileSync ( 'valid-ssl-key.pem' , 'utf8' ) ,
cert : fs . readFileSync ( 'valid-ssl-cert.pem' , 'utf8' )
}
} ) . listen ( 8009 ) ;
//
// Create the proxy server listening on port 443
//
httpProxy . createServer ( {
ssl : {
key : fs . readFileSync ( 'valid-ssl-key.pem' , 'utf8' ) ,
cert : fs . readFileSync ( 'valid-ssl-cert.pem' , 'utf8' )
} ,
target : 'https://localhost:9010' ,
secure : true // Depends on your needs, could be false.
} ) . listen ( 443 ) ;
//
// Create an HTTP proxy server with an HTTPS target
//
httpProxy . createProxyServer ( {
target : {
protocol : 'https:' ,
host : 'my-domain-name' ,
port : 443 ,
pfx : fs . readFileSync ( 'path/to/certificate.p12' ) ,
passphrase : 'password' ,
} ,
changeOrigin : true ,
} ) . listen ( 8000 ) ;
맨 위로 돌아가기
옵션에서 ws:true
사용하여 프록시에 대한 웹소켓 지원을 활성화할 수 있습니다.
//
// Create a proxy server for websockets
//
httpProxy . createServer ( {
target : 'ws://localhost:9014' ,
ws : true
} ) . listen ( 8014 ) ;
또한 ws(req, socket, head)
메소드를 호출하여 웹소켓 요청을 프록시할 수 있습니다.
//
// Setup our server to proxy standard HTTP requests
//
var proxy = new httpProxy . createProxyServer ( {
target : {
host : 'localhost' ,
port : 9015
}
} ) ;
var proxyServer = http . createServer ( function ( req , res ) {
proxy . web ( req , res ) ;
} ) ;
//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer . on ( 'upgrade' , function ( req , socket , head ) {
proxy . ws ( req , socket , head ) ;
} ) ;
proxyServer . listen ( 8015 ) ;
맨 위로 돌아가기
httpProxy.createProxyServer
다음 옵션을 지원합니다.
target : url 모듈로 구문 분석할 url 문자열
전달 : url 모듈로 구문 분석할 URL 문자열
에이전트 : http(s).request에 전달될 개체(노드의 https 에이전트 및 http 에이전트 개체 참조)
ssl : https.createServer()에 전달할 객체
ws : true/false, 웹소켓을 프록시하려는 경우
xfwd : true/false, x-forward 헤더를 추가합니다.
secure : SSL 인증서를 확인하려는 경우 true/false
toProxy : true/false, 절대 URL을 path
로 전달합니다(프록시로 프록싱하는 데 유용함).
prependPath : true/false, 기본값: true - 대상 경로를 프록시 경로 앞에 추가할지 여부를 지정합니다.
ignorePath : true/false, 기본값: false - 들어오는 요청의 프록시 경로를 무시할지 여부를 지정합니다(참고: 필요한 경우 /를 수동으로 추가해야 합니다).
localAddress : 나가는 연결을 위해 바인딩할 로컬 인터페이스 문자열
changeOrigin : true/false, 기본값: false - 호스트 헤더의 원본을 대상 URL로 변경합니다.
PreserveHeaderKeyCase : true/false, 기본값: false - 응답 헤더 키의 대소문자를 유지할지 여부를 지정합니다.
auth : 기본 인증, 즉 Authorization 헤더를 계산하기 위한 'user:password'입니다.
hostRewrite : (201/301/302/307/308) 리디렉션에서 호스트 이름 위치를 다시 씁니다.
autoRewrite : 요청된 호스트/포트를 기반으로 (201/301/302/307/308) 리디렉션에서 호스트/포트 위치를 다시 씁니다. 기본값: 거짓.
protocolRewrite : (201/301/302/307/308)의 위치 프로토콜을 'http' 또는 'https'로 리디렉션합니다. 기본값: null.
cookieDomainRewrite : set-cookie
헤더의 도메인을 다시 작성합니다. 가능한 값:
false
(기본값): 쿠키 재작성을 비활성화합니다.cookieDomainRewrite: "new.domain"
) 도메인을 제거하려면 cookieDomainRewrite: ""
사용하세요."*"
사용하세요. 예를 들어 하나의 도메인을 변경하지 않고 유지하고, 하나의 도메인을 다시 작성하고 다른 도메인을 제거합니다. cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
cookiePathRewrite : set-cookie
헤더의 경로를 다시 작성합니다. 가능한 값:
false
(기본값): 쿠키 재작성을 비활성화합니다.cookiePathRewrite: "/newPath/"
) 경로를 제거하려면 cookiePathRewrite: ""
사용하세요. 경로를 루트로 설정하려면 cookiePathRewrite: "/"
사용하세요."*"
를 사용하세요. 예를 들어 한 경로를 변경하지 않고 유지하려면 한 경로를 다시 작성하고 다른 경로를 제거하세요. cookiePathRewrite: {
"/unchanged.path/": "/unchanged.path/",
"/old.path/": "/new.path/",
"*": ""
}
headers : 대상 요청에 추가할 추가 헤더가 있는 개체입니다.
ProxyTimeout : 나가는 프록시 요청에 대한 시간 초과(밀리초)
timeout : 들어오는 요청에 대한 시간 제한(밀리초)
followRedirects : true/false, 기본값: false - 리디렉션을 따를지 여부를 지정합니다.
selfHandleResponse true/false, true로 설정된 경우 webOutgoing 패스가 호출되지 않으며 proxyRes
이벤트를 수신하고 이에 따라 응답을 적절하게 반환하는 것은 사용자의 책임입니다.
buffer : 요청 본문으로 보낼 데이터 스트림입니다. 아마도 요청 스트림을 프록시하기 전에 소비하는 미들웨어가 있을 수 있습니다. 예를 들어 요청 본문을 'req.rawbody'라는 필드로 읽는 경우 버퍼 옵션에서 이 필드를 다시 스트리밍할 수 있습니다.
'use strict';
const streamify = require('stream-array');
const HttpProxy = require('http-proxy');
const proxy = new HttpProxy();
module.exports = (req, res, next) => {
proxy.web(req, res, {
target: 'http://localhost:4003/',
buffer: streamify(req.rawBody)
}, next);
};
참고: options.ws
및 options.ssl
은 선택 사항입니다. options.target
및 options.forward
모두 누락될 수 없습니다.
proxyServer.listen
메서드를 사용하는 경우 다음 옵션도 적용 가능합니다.
맨 위로 돌아가기
error
: 대상에 대한 요청이 실패하면 오류 이벤트가 발생합니다. 클라이언트와 프록시 간에 전달되는 메시지, 프록시와 대상 간에 전달되는 메시지에 대해서는 오류 처리를 수행하지 않으므로 오류를 수신하고 처리하는 것이 좋습니다.proxyReq
: 이 이벤트는 데이터가 전송되기 전에 발생합니다. 이는 ProxyReq 요청 개체를 변경할 수 있는 기회를 제공합니다. "웹" 연결에 적용됩니다.proxyReqWs
: 이 이벤트는 데이터가 전송되기 전에 발생합니다. 이는 ProxyReq 요청 개체를 변경할 수 있는 기회를 제공합니다. "websocket" 연결에 적용됩니다.proxyRes
: 대상에 대한 요청이 응답을 받은 경우 이 이벤트가 발생합니다.open
: 이 이벤트는 프록시 웹소켓이 생성되어 대상 웹소켓으로 파이프되면 발생합니다.close
: 이 이벤트는 프록시 웹소켓이 닫히면 발생합니다.proxySocket
: open
위해 더 이상 사용되지 않습니다. var httpProxy = require ( 'http-proxy' ) ;
// Error example
//
// Http Proxy Server with bad target
//
var proxy = httpProxy . createServer ( {
target : 'http://localhost:9005'
} ) ;
proxy . listen ( 8005 ) ;
//
// Listen for the `error` event on `proxy`.
proxy . on ( 'error' , function ( err , req , res ) {
res . writeHead ( 500 , {
'Content-Type' : 'text/plain'
} ) ;
res . end ( 'Something went wrong. And we are reporting a custom error message.' ) ;
} ) ;
//
// Listen for the `proxyRes` event on `proxy`.
//
proxy . on ( 'proxyRes' , function ( proxyRes , req , res ) {
console . log ( 'RAW Response from the target' , JSON . stringify ( proxyRes . headers , true , 2 ) ) ;
} ) ;
//
// Listen for the `open` event on `proxy`.
//
proxy . on ( 'open' , function ( proxySocket ) {
// listen for messages coming FROM the target here
proxySocket . on ( 'data' , hybiParseAndLogMessage ) ;
} ) ;
//
// Listen for the `close` event on `proxy`.
//
proxy . on ( 'close' , function ( res , socket , head ) {
// view disconnected websocket connections
console . log ( 'Client disconnected' ) ;
} ) ;
맨 위로 돌아가기
var proxy = new httpProxy . createProxyServer ( {
target : {
host : 'localhost' ,
port : 1337
}
} ) ;
proxy . close ( ) ;
맨 위로 돌아가기
proxyRes
를 받은 후 자체 응답을 처리하려면 selfHandleResponse
를 사용하면 됩니다. 아래에서 볼 수 있듯이 이 옵션을 사용하면 proxyRes
가로채서 읽을 수 있지만 res
자체에 응답해야 합니다. 그렇지 않으면 원래 클라이언트는 어떤 데이터도 수신하지 않습니다.
var option = {
target : target ,
selfHandleResponse : true
} ;
proxy . on ( 'proxyRes' , function ( proxyRes , req , res ) {
var body = [ ] ;
proxyRes . on ( 'data' , function ( chunk ) {
body . push ( chunk ) ;
} ) ;
proxyRes . on ( 'end' , function ( ) {
body = Buffer . concat ( body ) . toString ( ) ;
console . log ( "res from proxied server:" , body ) ;
res . end ( "my response to cli" ) ;
} ) ;
} ) ;
proxy . web ( req , res , option ) ;
이 추가 기능 모듈을 통해 프록시 테이블 API를 사용할 수 있습니다. 이를 통해 일치하는 경로를 역방향 프록시가 통신할 대상 경로로 변환하는 규칙 세트를 정의할 수 있습니다.
$ npm test
Diego Pasquali가 만든 로고
맨 위로 돌아가기
master
와 달라야 함)맨 위로 돌아가기
MIT 라이센스(MIT)
저작권 (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger 및 기여자.
본 소프트웨어 및 관련 문서 파일("소프트웨어")의 사본을 취득한 모든 사람에게 사용, 복사, 수정, 병합에 대한 권리를 포함하되 이에 국한되지 않고 제한 없이 소프트웨어를 취급할 수 있는 권한이 무료로 부여됩니다. , 다음 조건에 따라 소프트웨어 사본을 게시, 배포, 재라이센스 부여 및/또는 판매하고, 소프트웨어를 제공받은 사람이 그렇게 하도록 허용합니다.
위의 저작권 고지와 본 허가 고지는 소프트웨어의 모든 사본 또는 상당 부분에 포함됩니다.
소프트웨어는 상품성, 특정 목적에의 적합성 및 비침해에 대한 보증을 포함하되 이에 국한되지 않고 명시적이든 묵시적이든 어떠한 종류의 보증 없이 "있는 그대로" 제공됩니다. 어떠한 경우에도 작성자나 저작권 보유자는 계약, 불법 행위 또는 기타 행위로 인해 소프트웨어나 사용 또는 기타 거래와 관련하여 발생하는 모든 청구, 손해 또는 기타 책임에 대해 책임을 지지 않습니다. 소프트웨어.