[node.js 응용] Build a Node.js Proxy Server in Under 10 minutes!

Build a Node.js Proxy Server in Under 10 minutes!

 

 

header - Build a Node.js Proxy Server in Under 10 minutes!

We have all heard the term “proxy”. It might sound like it’s some kind of portal to a new dimension from the Matrix movies, but it turns out it’s very real...and very useful!

In a nutshell, a proxy is an intermediary application which sits between two (or more) services and processes/modifies the requests and responses in both directions. This sounds complicated, I know, but let’s try with a simpler analogy:

Imagine you meet someone from Spain, but you don’t speak Spanish. What do you do? Well, you remember that your friend Santiago knows both Spanish and English and can translate for you.

people talking to each other in different languages asking about the other person's favorite music

The process goes like this:

  1. You tell something to Santiago in English
  2. Santiago translates it to Spanish in his head and says it in Spanish to your new friend
  3. Your new friend replies back to Santiago in Spanish
  4. Santiago then translates it in his head and tells you the response in English

Santiago in this case serves as a proxy between you and your new friend. You can’t speak directly to each other but thanks to the translator you can relay messages (i.e. requests and responses) and have a conversation!

Okay, now that we know what a proxy is, what are the use cases for it? Well, here are a few that we, at Twilio, find really useful:

  • Authorization - Forward only requests that are authorized to access a service
  • Load balancing - Distribute the requests equally among many instances
  • Logging - Log every requests going to a Back End API service
  • And many more...

Now that you know what a proxy is and why it is useful, let’s build a simple one using Node.js!

Prerequisites

 

To follow along, you need Node.js and Yarn installed, which are available on Mac, Windows and Linux distributions.

Build the simple Node.js proxy

 

In a few easy steps we are going to create a simple proxy in Node.js which can forward requests to multiple different servers/endpoints!

The full code which will be implemented step-by-step is available on GitHub here.

Initialize the project

 

Let’s start by initiating a new node project:

yarn init

This will generate a package.json file which will contain a basic project configuration. The command will prompt you with multiple questions (name, version, description, etc.) - you can click ‘Enter’ on all of them to accept the default values (for example, by default the entry point will be index.js).

Install dependencies

 

We need a few packages to make the proxy work:

which we can install by running:

yarn add express http-proxy-middleware morgan

Define a start command

 

We need to add a start command to our project, so after a small change, your package.json file should look like this (Depending on when you install these packages, some version numbers might differ, but their core functionality should stay the same. If the behaviour is drastically different, check their latest documentations.):

{
 "name": "simple-nodejs-proxy",
 "version": "1.0.0",
 "main": "index.js",
 "license": "MIT",
 "dependencies": {
   "express": "^4.17.1",
   "http-proxy-middleware": "^1.0.5",
   "morgan": "^1.10.0"
 },
 "scripts": {
   "start": "node index.js"
 }
}

If we now add an empty file index.js, we can execute the project through:

yarn start

This should run the file. Because the file is empty the console output should also be empty.

But enough configurations, let’s actually proxy some requests!

Create a simple proxy

 

This is where the interesting bits begin. Go ahead and open the index.js file and add the necessary imports:

const express = require('express');
const morgan = require("morgan");
const { createProxyMiddleware } = require('http-proxy-middleware');

Now we can create a basic express server and define some constants which we will use later:

// Create Express Server
const app = express();

// Configuration
const PORT = 3000;
const HOST = "localhost";
const API_SERVICE_URL = "https://jsonplaceholder.typicode.com";

Before we implement the proxy logic, we can add the morgan middleware which logs the incoming requests:

// Logging
app.use(morgan('dev'));

To be able to test that we proxy only what we want, let’s add a mock /info endpoint which doesn’t forward the request, but rather returns a simple text response:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

// Info GET endpoint
app.get('/info', (req, res, next) => {
   res.send('This is a proxy service which proxies to Billing and Account APIs.');
});

Before defining the proxy endpoints, let’s also add a simple authorization/permission handling middleware which sends 403 (Forbidden) if the Authorization Header is missing:

// Authorization
app.use('', (req, res, next) => {
   if (req.headers.authorization) {
       next();
   } else {
       res.sendStatus(403);
   }
});

Then we define the proxy endpoint. We want to proxy all requests starting with /json_placeholder to the notorious JSONPlaceholder API (a simple mock API which contains multiple endpoints supporting all HTTP methods). We also define a pathRewrite so that /json_placeholder is omitted when forwarded to the API:

// Proxy endpoints
app.use('/json_placeholder', createProxyMiddleware({
   target: API_SERVICE_URL,
   changeOrigin: true,
   pathRewrite: {
       [`^/json_placeholder`]: '',
   },
}));

This way, when we, for example, send a request to localhost:3000/json_placeholder/posts/1, the URL will be rewritten to <API_SERVICE_URL>/posts/1 (in this case: https://jsonplaceholder.typicode.com/posts/1), thus removing /json_placeholder which the API doesn’t need.

And, last but not least, we start the configured server with this function call:

// Start the Proxy
app.listen(PORT, HOST, () => {
   console.log(`Starting Proxy at ${HOST}:${PORT}`);
});

Run the proxy

 

Let’s start the proxy with the following command:

yarn start

This prints something along the lines of:

yarn run v1.22.4
$ node index.js
[HPM] Proxy created: /  -> https://jsonplaceholder.typicode.com
[HPM] Proxy rewrite rule created: "^/json_placeholder" ~> ""
Starting Proxy at localhost:3000

The proxy should now be running and if we open a second terminal and send a GET request to the /info:

curl localhost:3000/info

We should receive a response from our proxy. And, unsurprisingly, we get:

This is a proxy service which proxies to JSONPlaceholder API.

Okay, this is great and all, but we don’t want some boring GET endpoints, we want to proxy!

In order to test the proxying, we can send a new GET request like this:

curl localhost:3000/json_placeholder/posts/1

man saying oh no

 

Oh, no! This returns:

Forbidden

Fear not, this is expected because we included the authorization middleware which requires that every request contains an Authorization Header. So, make this small modification (you can even change it to your name because due to the simplicity of our authorization step, every name would work!):

curl -H "Authorization: nikolay" localhost:3000/json_placeholder/posts/1

This gives us:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Hooray! Your first successfully proxied request! We can even try this with a POST request:

curl -X POST -H "Authorization: real_user" --data '{"title": "Build a Node.js Proxy Server in Under 10 minutes!","body": "We have all heard the term "proxy"...",userId="1"}' localhost:3000/json_placeholder/posts

The POST request works as expected:

{
  "{\"title\": \"Build a Node.js Proxy Server in Under 10 minutes!\",\"body\": \"We have all heard the term "proxy"...\",userId": "\"1\"}",
  "id": 101
}

For the full code, check the Github repository.

What’s next for Node.js proxy servers?

 

This is an extremely simple version of a proxy. It’s barebones but it works! Depending on your use case, you can extend it by:

http-proxy-middleware is a simple, yet powerful library and there are a lot of properties you can modify to achieve your specific goals, so check out its documentation to do something more complex.

Conclusion

 

Maybe before reading this article you didn’t know what a proxy is or maybe you thought it’s really hard to build one yourself. As you can see, it’s quite the opposite! We built a simple one, yes, but now you know the basics and you have everything you need to make this simple proxy more complex, more efficient or maybe just a bit more fun! So go ahead and flex to your colleagues and friends with your newly learned Proxy skills!

[출처] https://www.twilio.com/blog/node-js-proxy-server

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
27 [wordpress, 워드프레스] 워드프레스로 쉽게 랜딩 페이지 만들기 (feat. 엘리멘터, GeneratePress, Divi) file 졸리운_곰 2024.12.20 545
26 [wordpress, 워드프레스] WordPress 페이지또는 글에 별도 CSS와 JavaScript 추가하기 file 졸리운_곰 2024.12.19 354
25 [wordpress 플러그인] 코스모스팜. 회원관리 1.메뉴에 로그인 넣기 file 졸리운_곰 2024.08.25 513
24 [wordpress 플러그인] WP-Members로 회원제 사이트 만들기 file 졸리운_곰 2024.08.25 749
23 [php worldpress] 워드프레스 새 서버 이전시 페이지 안나오는 문제 : How to Rewrite URLs with mod_rewrite for Apache on Ubuntu 20.04 file 졸리운_곰 2024.08.07 774
22 [php worldpress] PHP query to SQL server database (wordpress) 졸리운_곰 2024.07.28 503
21 [php worldpress] [위 에]wordpress 사용자 암호 화 원리 및 알고리즘 분석 졸리운_곰 2022.04.11 377
20 [wordpress] WPForms 워드프레스 폼빌더 사용법 file 졸리운_곰 2021.04.25 1715
19 [wordpress][워드프레스] 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.04.15 356
18 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.01.12 459
17 워드프레스 – CRUD file 졸리운_곰 2021.01.02 501
16 워드프레스 데이터베이스 들여다보기. file 졸리운_곰 2020.08.04 673
15 워드프레스 플러그인과 테마 비교 - 사이트별 플러그인 만들기 졸리운_곰 2020.04.21 501
14 워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하는 방법 졸리운_곰 2020.04.21 736
13 워드프레스 플러그인 만들기 file 졸리운_곰 2020.04.21 500
12 워드프레스 숏코드: 완벽 가이드 file 졸리운_곰 2020.04.21 513
11 워드프레스 페이지 분석 file 졸리운_곰 2019.11.19 515
10 내가 본 워드프레스 핵심 구조 및 기능 (Wordpress Architecture and Function) file 졸리운_곰 2019.11.19 452
9 Embedding three.js in WordPress 워드프레스에서 three.js 사용 졸리운_곰 2019.11.08 517
8 How to Super Charge your WordPress with Microservices 워드프레스 마이크로서비스 file 졸리운_곰 2019.11.03 373
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED