Express Proxy Request To Another Server

E

Proxy with express.js - Stack Overflow

Proxy with express.js – Stack Overflow

To avoid same-domain AJAX issues, I want my web server to forward all requests from URL /api/BLABLA to another server, for example, and return to user the same thing that this remote server returned, transparently.
All other URLs (beside /api/*) are to be served directly, no proxying.
How do I achieve this with + Can you give a simple code example?
(both the web server and the remote 3000 server are under my control, both running with)
So far I found this, but reading the documentation there didn’t make me any wiser. I ended up with
var proxy = new utingProxy();
(“/api/*”, function(req, res) {
(“old request url ” +)
= ‘/’ + (‘/’)(2)(‘/’); // remove the ‘/api’ part
(“new request url ” +)
oxyRequest(req, res, {
host: “”,
port: 3000});});
but nothing is returned to the original web server (or to the end user), so no luck.
tanguy_k9, 5175 gold badges46 silver badges51 bronze badges
asked May 3 ’12 at 16:20
2
request has been deprecated as of February 2020, I’ll leave the answer below for historical reasons, but please consider moving to an alternative listed in this issue.
Archive
I did something similar but I used request instead:
var request = require(‘request’);
(‘/’, function(req, res) {
//modify the url in any way you want
var newurl = ”;
request(newurl)(res);});
I hope this helps, took me a while to realize that I could do this:)
answered Jun 4 ’13 at 17:56
trigomantrigoman3, 3552 gold badges20 silver badges20 bronze badges
10
I found a shorter and very straightforward solution which works seamlessly, and with authentication as well, using express–proxy:
const url = require(‘url’);
const proxy = require(‘express–proxy’);
// New hostname+path as specified by question:
const apiProxy = proxy(”, {
proxyReqPathResolver: req => (seUrl)});
And then simply:
(‘/api/*’, apiProxy);
Note: as mentioned by @MaxPRafferty, use req. originalUrl in place of baseUrl to preserve the querystring:
forwardPath: req => (seUrl)
Update: As mentioned by Andrew (thank you! ), there’s a ready-made solution using the same principle:
npm i –save -proxy-middleware
And then:
const proxy = require(‘-proxy-middleware’)
var apiProxy = proxy(‘/api’, {target: ”});
(apiProxy)
Documentation: -proxy-middleware on Github
I know I’m late to join this party, but I hope this helps someone.
answered Sep 24 ’15 at 8:40
SelfishSelfish5, 3503 gold badges36 silver badges58 bronze badges
8
You want to use quest to create a similar request to the remote API and return its response.
Something like this:
const = require(”);
// or use import from ”;
/* your app config here */
(‘/api/BLABLA’, (oreq, ores) => {
const options = {
// host to forward to
host: ”,
// port to forward to
port: 80,
// path to forward to
path: ‘/api/BLABLA’,
// request method
method: ‘POST’,
// headers to send
headers: oreq. headers, };
const creq =. request(options, pres => {
// set encoding
tEncoding(‘utf8’);
// set status code based on proxied response
ores. writeHead(atusCode);
// wait for data
(‘data’, chunk => {
(chunk);});
(‘close’, () => {
// closed, let’s end client request as well
();});
(‘end’, () => {
// finished, let’s finish client request as well
();});})
(‘error’, e => {
// we got an error
(ssage);
try {
// attempt to set error message and status
ores. writeHead(500);
(ssage);} catch (e) {
// ignore}
Notice: I haven’t really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.
answered May 3 ’12 at 16:47
mekwallmekwall27. 4k6 gold badges69 silver badges72 bronze badges
6
To extend trigoman’s answer (full credits to him) to work with POST (could also make work with PUT etc):
(‘/api’, function(req, res) {
var url = ‘YOUR_API_BASE_URL’+;
var r = null;
if( === ‘POST’) {
r = ({uri: url, json:});} else {
r = request(url);}
(r)(res);});
answered Mar 11 ’14 at 13:01
4
I used the following setup to direct everything on /rest to my backend server (on port 8080), and all other requests to the frontend server (a webpack server on port 3001). It supports all HTTP-methods, doesn’t lose any request meta-info and supports websockets (which I need for hot reloading)
var express = require(‘express’);
var app = express();
var Proxy = require(‘-proxy’);
var apiProxy = eateProxyServer();
var backend = ‘localhost:8080’,
frontend = ‘localhost:3001’;
(“/rest/*”, function(req, res) {
(req, res, {target: backend});});
(“/*”, function(req, res) {
(req, res, {target: frontend});});
var server = require(”). createServer(app);
(‘upgrade’, function (req, socket, head) {
(req, socket, head, {target: frontend});});
(3000);
answered May 7 ’16 at 8:14
Anthony De SmetAnthony De Smet1, 9173 gold badges13 silver badges22 bronze badges
1
First install express and -proxy-middleware
npm install express -proxy-middleware –save
Then in your
const express = require(‘express’);
const proxy = require(‘-proxy-middleware’);
const app = express();
((‘client’));
// Add middleware for proxying
const apiProxy = proxy(‘/api’, { target: ‘localhost:8080’});
(‘/api’, apiProxy);
// Render your site
const renderIndex = (req, res) => {
ndFile(solve(__dirname, ‘client/’));}
(‘/*’, renderIndex);
(3000, () => {
(‘Listening on: localhost:3000’);});
In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.
localhost:3000/api/login redirect to localhost:8080/api/login
answered Jan 17 ’17 at 16:52
C. DupetitC. Dupetit1511 silver badge4 bronze badges
0
Ok, here’s a ready-to-copy-paste answer using the require(‘request’) npm module and an environment variable *instead of an hardcoded proxy):
coffeescript
(req, res, next) ->
r = false
method = (). replace(/delete/, ‘del’)
switch method
when ‘get’, ‘post’, ‘del’, ‘put’
r = request[method](
uri: +
json:)
else
return (‘invalid method’)
(r) res
javascript:
(function(req, res, next) {
var method, r;
method = (). replace(/delete/, “del”);
switch (method) {
case “get”:
case “post”:
case “del”:
case “put”:
r = request[method]({
uri: +,
json:});
break;
default:
return (“invalid method”);}
return (r)(res);});
answered Apr 20 ’15 at 15:50
I found a shorter solution that does exactly what I want
After installing -proxy
npm install -proxy –save
Use it like below in your server/index/
var proxyServer = require(‘-route-proxy’);
(‘/api/BLABLA/’, nnect({
to: ”, : true,
route: [‘/’]}));
I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.
Hope it is going to help someone else too:)
answered Oct 18 ’16 at 20:39
hzitounhzitoun4, 43430 silver badges39 bronze badges
I think you should use cors npm
const cors = require(‘cors’);
var corsOptions = {
origin: ‘localhost:3000’,
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204}
(cors(corsOptions));
answered Apr 6 at 2:01
I don’t have have an express sample, but one with plain -proxy package. A very strip down version of the proxy I used for my blog.
In short, all nodejs proxy packages work at the protocol level, not tcp(socket) level. This is also true for express and all express middleware. None of them can do transparent proxy, nor NAT, which means keeping incoming traffic source IP in the packet sent to backend web server.
However, web server can pickup original IP from x-forwarded headers and add it into the log.
The xfwd: true in proxyOption enable x-forward header feature for -proxy.
const proxy = require(‘-proxy’);
proxyConfig = {
Port: 8888,
proxyOptions: {
target: {
port: 80},
xfwd: true // <--- This is what you are looking for. }}; function startProxy() { proxy. createServer(oxyOptions) (tpPort, '0. 0. 0');} startProxy(); Reference for X-Forwarded Header: Full version of my proxy: answered Mar 24 '17 at 5:44 John SiuJohn Siu4, 8652 gold badges23 silver badges43 bronze badges Not the answer you're looking for? Browse other questions tagged proxy express reverse-proxy or ask your own question. Build a Node.js Proxy Server in Under 10 minutes! - Twilio

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

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 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.
The process goes like this:
You tell something to Santiago in English
Santiago translates it to Spanish in his head and says it in Spanish to your new friend
Your new friend replies back to Santiago in Spanish
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!
Prerequisites
To follow along, you need and Yarn installed, which are available on Mac, Windows and Linux distributions.
Build the simple proxy
In a few easy steps we are going to create a simple proxy in 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:
This will generate a 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).
Install dependencies
We need a few packages to make the proxy work:
express: Minimalist web framework
-proxy-middleware: Simple proxy framework
(optional) morgan – HTTP request logger middleware
which we can install by running:
yarn add express -proxy-middleware morgan
Define a start command
We need to add a start command to our project, so after a small change, your 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”: “”,
“license”: “MIT”,
“dependencies”: {
“express”: “^4. 17. 1”,
“-proxy-middleware”: “^1. 5”,
“morgan”: “^1. 10. 0”},
“scripts”: {
“start”: “node “}}
If we now add an empty file, we can execute the project through:
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 file and add the necessary imports:
const express = require(‘express’);
const morgan = require(“morgan”);
const { createProxyMiddleware} = require(‘-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 = “;
Before we implement the proxy logic, we can add the morgan middleware which logs the incoming requests:
// Logging
(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:
// Info GET endpoint
(‘/info’, (req, res, next) => {
(‘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
(”, (req, res, next) => {
if (thorization) {
next();} else {
ndStatus(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
(‘/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 /posts/1 (in this case:), 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
(PORT, HOST, () => {
(`Starting Proxy at ${HOST}:${PORT}`);});
Run the proxy
Let’s start the proxy with the following command:
This prints something along the lines of:
yarn run v1. 22. 4
$ node
[HPM] Proxy created: / -> [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:
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
Oh, no! This returns:
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 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 Proxy Server in Under 10 minutes! \””
\

\””body\””: \””We have all heard the term “”proxy””… \””

userId””: “”\””1\””}””

Frequently Asked Questions about express proxy request to another server

About the author

proxyreview

If you 're a SEO / IM geek like us then you'll love our updates and our website. Follow us for the latest news in the world of web automation tools & proxy servers!

By proxyreview

Recent Posts

Useful Tools