Node.js 프록시는 간단하게 만들었습니다. Connect, Express, Next.js 등을 쉽게 구성하여 프록시 미들웨어를 구성하십시오.
인기있는 nodejitsu http-proxy 로 구동됩니다.
이 페이지는 버전 v3.xx (릴리스 노트)에 대한 설명서를 보여줍니다.
v2.xx에서 v3.xx로 마이그레이션하는 방법에 대한 자세한 내용은 Migration.md를 참조하십시오.
오래된 문서를 찾고 있다면. 이동 :
프록시 /api http://www.example.org 에 요청합니다
팁 : 이름 기반 가상 호스팅 사이트의 옵션 changeOrigin true 로 설정하십시오.
// typescript
import * as express from 'express' ;
import type { Request , Response , NextFunction } from 'express' ;
import { createProxyMiddleware } from 'http-proxy-middleware' ;
import type { Filter , Options , RequestHandler } from 'http-proxy-middleware' ;
const app = express ( ) ;
const proxyMiddleware = createProxyMiddleware < Request , Response > ( {
target : 'http://www.example.org/api' ,
changeOrigin : true ,
} ) ;
app . use ( '/api' , proxyMiddleware ) ;
app . listen ( 3000 ) ;
// proxy and keep the same base path "/api"
// http://127.0.0.1:3000/api/foo/bar -> http://www.example.org/api/foo/bar 모든 http-proxy 옵션은 추가 http-proxy-middleware 옵션과 함께 사용할 수 있습니다.
pathFilter (String, [] String, Glob, [] glob, function)pathRewrite (객체/기능)router (객체/기능)plugins (배열)ejectPlugins (부울) 기본값 : falselogger (객체)http-proxy 이벤트http-proxy 옵션npm install --save-dev http-proxy-middleware createProxyMiddleware(config) 사용하여 프록시 미들웨어를 작성하고 구성합니다.
const { createProxyMiddleware } = require ( 'http-proxy-middleware' ) ;
const apiProxy = createProxyMiddleware ( {
target : 'http://www.example.org' ,
changeOrigin : true ,
} ) ;
// 'apiProxy' is now ready to be used as middleware in a server.target : 대상 호스트를 대상으로 대상으로합니다. (프로토콜 + 호스트)
옵션 .Changeorigin : 가상 호스팅 사이트의 경우
http-proxy-middleware 구성 옵션의 전체 목록을 참조하십시오
express Server의 예.
// include dependencies
const express = require ( 'express' ) ;
const { createProxyMiddleware } = require ( 'http-proxy-middleware' ) ;
const app = express ( ) ;
// create the proxy
/** @type {import('http-proxy-middleware/dist/types').RequestHandler<express.Request, express.Response>} */
const exampleProxy = createProxyMiddleware ( {
target : 'http://www.example.org/api' , // target host with the same base path
changeOrigin : true , // needed for virtual hosted sites
} ) ;
// mount `exampleProxy` in web server
app . use ( '/api' , exampleProxy ) ;
app . listen ( 3000 ) ; 서버의 app.use path 매개 변수를 사용하려면 요청과 일치합니다. pathFilter 옵션을 사용하여 프록시하려는 요청을 추가로 포함/제외하십시오.
app . use (
createProxyMiddleware ( {
target : 'http://www.example.org/api' ,
changeOrigin : true ,
pathFilter : '/api/proxy-only-this-path' ,
} ) ,
) ; app.use 문서 :
HTTP-Proxy-Middleware 옵션 :
pathFilter (String, [] String, Glob, [] glob, function) 어떤 요청을 프록스 해야하는지 좁 힙니다. 필터링에 사용되는 path 는 request.url pathname입니다. Express에서 이것은 대리의 마운트 포인트와 관련된 path 입니다.
경로 일치
createProxyMiddleware({...}) - 모든 경로와 일치하면 pathFilter 구성되지 않은 경우 모든 요청이 프록시됩니다.createProxyMiddleware({ pathFilter: '/api', ...}) - /api 로 시작하는 경로와 일치다중 경로 일치
createProxyMiddleware({ pathFilter: ['/api', '/ajax', '/someotherpath'], ...})와일드 카드 경로 일치
세밀한 제어를 위해 와일드 카드 매칭을 사용할 수 있습니다. 글로벌 패턴 매칭은 마이크로 치로 수행됩니다. 더 많은 글로브 예제를 보려면 Micromatch 또는 Glob을 방문하십시오.
createProxyMiddleware({ pathFilter: '**', ...}) 모든 경로와 일치하면 모든 요청이 프록시됩니다.createProxyMiddleware({ pathFilter: '**/*.html', ...}) .html 로 끝나는 모든 경로와 일치합니다.createProxyMiddleware({ pathFilter: '/*.html', ...}) Path-Absolute 바로 아래 경로와 일치합니다createProxyMiddleware({ pathFilter: '/api/**/*.html', ...}) /api 경로에서 .html 로 끝나는 요청과 일치합니다.createProxyMiddleware({ pathFilter: ['/api/**', '/ajax/**'], ...}) 여러 패턴을 결합합니다createProxyMiddleware({ pathFilter: ['/api/**', '!**/bad.json'], ...}) 제외참고 : 다중 경로 일치에서는 문자열 경로와 와일드 카드 경로를 함께 사용할 수 없습니다.
맞춤형 일치
전체 제어를 위해서는 사용자 정의 기능을 제공하여 어떤 요청을 프록시 해야하는지 결정할 수 있습니다.
/**
* @return {Boolean}
*/
const pathFilter = function ( path , req ) {
return path . match ( '^/api' ) && req . method === 'GET' ;
} ;
const apiProxy = createProxyMiddleware ( {
target : 'http://www.example.org' ,
pathFilter : pathFilter ,
} ) ;pathRewrite (객체/기능)대상의 URL 경로를 다시 작성하십시오. 객체 키는 경로와 일치하는 regexp 로 사용됩니다.
// rewrite path
pathRewrite: { '^/old/api' : '/new/api' }
// remove path
pathRewrite: { '^/remove/api' : '' }
// add base path
pathRewrite: { '^/' : '/basepath/' }
// custom rewriting
pathRewrite: function ( path , req ) { return path . replace ( '/api' , '/base/api' ) }
// custom rewriting, returning Promise
pathRewrite: async function ( path , req ) {
const should_add_something = await httpRequestToDecideSomething ( path ) ;
if ( should_add_something ) path += "something" ;
return path ;
}router (객체/기능) re-target 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://127.0.0.1:8001' , // host only
'staging.localhost:3000' : 'http://127.0.0.1:8002' , // host only
'localhost:3000/api' : 'http://127.0.0.1:8003' , // host + path
'/rest' : 'http://127.0.0.1:8004' // path only
}
// Custom router function (string target)
router: function ( req ) {
return 'http://127.0.0.1:8004' ;
}
// Custom router function (target object)
router: function ( req ) {
return {
protocol : 'https:' , // The : is required
host : '127.0.0.1' ,
port : 8004
} ;
}
// Asynchronous router function which returns promise
router: async function ( req ) {
const url = await doSomeIO ( ) ;
return url ;
}plugins (배열) const simpleRequestLogger = ( proxyServer , options ) => {
proxyServer . on ( 'proxyReq' , ( proxyReq , req , res ) => {
console . log ( `[HPM] [ ${ req . method } ] ${ req . url } ` ) ; // outputs: [HPM] GET /users
} ) ;
} ,
const config = {
target : `http://example.org` ,
changeOrigin : true ,
plugins : [ simpleRequestLogger ] ,
} ;ejectPlugins (부울) 기본값 : false 사전 구성된 플러그인에 만족하지 않으면 ejectPlugins: true 구성하여이를 꺼낼 수 있습니다.
참고 : 서버가 충돌하지 않도록 고유 한 오류 처리기를 등록하십시오.
// eject default plugins and manually add them back
const {
debugProxyErrorsPlugin , // subscribe to proxy errors to prevent server from crashing
loggerPlugin , // log proxy events to a logger (ie. console)
errorResponsePlugin , // return 5xx response on proxy error
proxyEventsPlugin , // implements the "on:" option
} = require ( 'http-proxy-middleware' ) ;
createProxyMiddleware ( {
target : `http://example.org` ,
changeOrigin : true ,
ejectPlugins : true ,
plugins : [ debugProxyErrorsPlugin , loggerPlugin , errorResponsePlugin , proxyEventsPlugin ] ,
} ) ;logger (객체) HTTP-Proxy-Middleware에서 정보를 출력하기 위해 로거를 구성하십시오. console , winston , pino , bunyan , log4js 등 ...
info , warn , error 만 다른 로거의 호환성을 위해 내부적으로 사용됩니다.
winston 사용하는 경우 보간을 활성화하십시오 : https://github.com/winstonjs/winston#string-nterpolation
자세한 내용은 Logger Recipes (Recipes/Logger.md)를 참조하십시오.
createProxyMiddleware ( {
logger : console ,
} ) ; http-proxy 이벤트 on 옵션으로 HTTP-Proxy 이벤트를 구독하십시오.
createProxyMiddleware ( {
target : 'http://www.example.org' ,
on : {
proxyReq : ( proxyReq , req , res ) => {
/* handle proxyReq */
} ,
proxyRes : ( proxyRes , req , res ) => {
/* handle proxyRes */
} ,
error : ( err , req , res ) => {
/* handle error */
} ,
} ,
} ) ; Option.on.error : 함수, 사용자 정의 오류 처리에 대한 HTTP-Proxy의 error 이벤트를 구독하십시오.
function onError ( err , req , res , target ) {
res . writeHead ( 500 , {
'Content-Type' : 'text/plain' ,
} ) ;
res . end ( 'Something went wrong. And we are reporting a custom error message.' ) ;
} 옵션 proxyRes
function onProxyRes ( proxyRes , req , res ) {
proxyRes . headers [ 'x-added' ] = 'foobar' ; // add new header to response
delete proxyRes . headers [ 'x-removed' ] ; // remove header from response
} Option.on.proxyReq : 함수, HTTP-Proxy의 proxyReq 이벤트를 구독하십시오.
function onProxyReq ( proxyReq , req , res ) {
// add custom header to request
proxyReq . setHeader ( 'x-added' , 'foobar' ) ;
// or log the req
} Option.on.proxyReqws : 함수, HTTP-Proxy의 proxyReqWs 이벤트를 구독하십시오.
function onProxyReqWs ( proxyReq , req , socket , options , head ) {
// add custom header
proxyReq . setHeader ( 'X-Special-Proxy-Header' , 'foobar' ) ;
} Option.on.open : 함수, HTTP-Proxy의 open 이벤트를 구독하십시오.
function onOpen ( proxySocket ) {
// listen for messages coming FROM the target here
proxySocket . on ( 'data' , hybridParseAndLogMessage ) ;
} 옵션 close
function onClose ( res , socket , head ) {
// view disconnected websocket connections
console . log ( 'Client disconnected' ) ;
} http-proxy 옵션다음 옵션은 기본 HTTP-Proxy 라이브러리에서 제공합니다.
옵션 .Target : URL 모듈로 구문 분석 할 URL 문자열
옵션 : URL 모듈로 구문 분석 할 URL 문자열
옵션 .Agent : HTTP로 전달할 객체 .request (Node의 HTTPS 에이전트 및 HTTP 에이전트 객체 참조)
옵션 .ssl : https.createserver ()로 전달할 객체
옵션 .ws : true/false : websockets를 프록시하려는 경우
옵션 .xfwd : true/false, x-forward 헤더가 추가됩니다
SSL CERTS를 확인하려면 옵션 .
toproxy : true/false, 절대 URL을 path 로 전달합니다 (프록시를 프록시로 프록시하는 데 유용함)
옵션 .prependpath : true/false, default : true- 대상의 경로를 프록시 경로로 선출할지 여부를 지정합니다.
옵션. indorepath : true / false, default : false- 들어오는 요청의 프록시 경로를 무시할지 여부를 지정합니다 (참고 : 필요한 경우 수동으로 추가해야합니다).
옵션 .LocalAddress : 발신 연결을 위해 바인딩 할 로컬 인터페이스 문자열
옵션 .changeorigin : true/false, default : false- 호스트 헤더의 원점을 대상 URL로 변경
옵션 .PreserveHeaderKeyCase : True/False, Default : False- 응답 헤더 키의 문자 케이스를 유지할지 여부를 지정합니다.
옵션. Auth : 기본 인증, 즉 '사용자 : 암호'인증 헤더를 계산합니다.
옵션 .hostrewrite : (301/302/307/308) 리디렉션에서 위치 호스트 이름을 다시 작성합니다.
AUTOREWRITE : 요청 된 호스트/포트를 기반으로 (301/302/307/308) 위치 호스트/포트를 다시 작성합니다. 기본값 : False.
옵션 .protocolrewrite : (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/ " ,
"*" : " "
} 옵션. 헤더 : 객체, 요청 헤더를 추가합니다. (예 : {host:'www.example.org'} )
옵션 .proxyTimeout : proxy가 대상으로부터 응답이 없을 때 시간 초과 (Millis)
옵션. 타임 아웃 : 수신 요청에 대한 타임 아웃 (millis)
옵션 .FollowRedirects : true/false, default : false- 리디렉션을 따르겠다고 지정합니다.
selfhandleresponse true/false, true로 설정된 경우, 웹 아웃중인 패스는 호출되지 않으며 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://127.0.0.1:4003/' ,
buffer : streamify ( req . rawBody ) ,
} ,
next ,
) ;
} ; // verbose api
createProxyMiddleware ( { pathFilter : '/' , target : 'http://echo.websocket.org' , ws : true } ) ; 이전 WebSocket 예제에서 HTTP-Proxy-Middleware는 HTTP upgrade 이벤트를 듣기 위해 초기 HTTP 요청에 의존합니다. 초기 HTTP 요청없이 WebSocket을 프록시 해야하는 경우 서버의 HTTP upgrade 이벤트를 수동으로 구독 할 수 있습니다.
const wsProxy = createProxyMiddleware ( { target : 'ws://echo.websocket.org' , changeOrigin : true } ) ;
const app = express ( ) ;
app . use ( wsProxy ) ;
const server = app . listen ( 3000 ) ;
server . on ( 'upgrade' , wsProxy . upgrade ) ; // <-- subscribe to http 'upgrade' createProxyMiddleware 에서 onProxyReq 정의하여 다운 스트림의 요청을 가로 채립니다.
현재 유일하게 사전 예상 된 요청 인터셉터는 fixRequestBody 입니다.이 중간에 bodyParser 적용될 때 프록시 포스트 요청을 수정하는 데 사용됩니다.
예:
const { createProxyMiddleware , fixRequestBody } = require ( 'http-proxy-middleware' ) ;
const proxy = createProxyMiddleware ( {
/**
* Fix bodyParser
**/
on : {
proxyReq : fixRequestBody ,
} ,
} ) ; responseInterceptor 로 업스트림에서 응답을 가로 채립니다. ( selfHandleResponse: true )
brotli , gzip 및 deflate 로 압축되는 응답은 자동으로 압축 해제됩니다. 응답은 조작 할 수있는 buffer (DOCS)로 반환됩니다.
buffer 사용하면 응답 조작이 텍스트 응답 (HTML/CSS/JS 등)에만 국한되지 않습니다. 이미지 조작도 가능합니다. (예)
참고 : responseInterceptor 대상 응답 스트리밍을 비활성화합니다.
예:
const { createProxyMiddleware , responseInterceptor } = require ( 'http-proxy-middleware' ) ;
const proxy = createProxyMiddleware ( {
/**
* IMPORTANT: avoid res.end being called automatically
**/
selfHandleResponse : true , // res.end() will be called internally by responseInterceptor()
/**
* Intercept response and replace 'Hello' with 'Goodbye'
**/
on : {
proxyRes : responseInterceptor ( async ( responseBuffer , proxyRes , req , res ) => {
const response = responseBuffer . toString ( 'utf8' ) ; // convert buffer to string
return response . replace ( 'Hello' , 'Goodbye' ) ; // manipulate response and return the result
} ) ,
} ,
} ) ;더 많은 예를 보려면 인터셉트 레시피를 확인하십시오.
Node.js 17+는 더 이상 DNS 조회 용 IPv6보다 IPv4를 선호하지 않습니다. 예를 들어 localhost 127.0.0.1 로 해결 될 것이라고 보장 하지는 않습니다 . ::1 (또는 다른 IP 주소) 일 수도 있습니다.
대상 서버가 IPv4 연결 만 수락하는 경우 ::1 (IPv6)로 해결되면 localhost 로 프록시를 시도하면 실패합니다.
그것을 해결하는 방법 :
target: "http://localhost" to target: "http://127.0.0.1" (IPv4).node 실행할 때이 플래그를 추가하십시오 : node index.js --dns-result-order=ipv4first . (권장되지 않습니다.)참고 : Happy Eyeballs라는 것은 IPv4와 IPv6에 모두 병렬로 연결되는 것을 의미합니다. Node.js에는없는 것이지만
curl연결할 수있는 이유를 설명합니다.
DEBUG 환경 변수 활성화 디버그 로깅 구성.
더 많은 옵션은 debug 프로젝트를 참조하십시오.
DEBUG=http-proxy-middleware * node server.js
$ http-proxy-middleware proxy created +0ms
$ http-proxy-middleware proxying request to target: ' http://www.example.org ' +359ms작업 예제를보고 놀십시오.
일반적인 사용 사례에 대한 레시피를보십시오.
http-proxy-middleware 다음 서버와 호환됩니다.
샘플 구현은 서버 레시피에서 찾을 수 있습니다.
테스트 스위트 실행 :
# install dependencies
$ yarn
# linting
$ yarn lint
$ yarn lint:fix
# building (compile typescript to js)
$ yarn build
# unit tests
$ yarn test
# code coverage
$ yarn cover
# check spelling mistakes
$ yarn spellcheckMIT 라이센스 (MIT)
저작권 (C) 2015-2024 Steven Chim