Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express proxy API calls with cookie

I am using express where i have mocked API calls for my application.

Is there any proxy that I can use to redirect my calls to my dev server ?

below is my sample express code

var express = require('express');
var app = express();
var path = require('path');
var cors = require('cors');


app.use(express.static(path.join(__dirname, 'public'))); 
app.use(express.static(path.join(__dirname, 'dist'))); 

app.get('/brand', function(req,res){
    res.send({"brand":"Cadillac","origin":"USA"});
});

When I run my application in local the API's from my code "http://localhost:3000/brand" should redirect to "http://www-dev.abc.com/brand"

Before redirecting I also need to set a cookie, as the API gives data only when there is a valid cookie.

Is there any Proxy that I can use ? Could you provide any examples ?

like image 735
user804401 Avatar asked Dec 18 '17 14:12

user804401


1 Answers

If I understand you right, then your requirements list looks like:

  1. Simple integration with express.
  2. Proxy only one endpoint.
  3. Proxy only on local environment.
  4. Ability to set cookies for proxied request.

Code Example:

var express = require('express');
var app = express();
var path = require('path');
var proxy = require('express-http-proxy');

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'dist')));

if (process.env.NODE_ENV === 'production') {
  app.get('/brand', function(req,res){
    res.send({"brand":"Cadillac","origin":"USA"});
  });
} else {
  app.use('/brand', proxy('http://www-dev.abc.com/brand', {
    proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
      proxyReqOpts.headers['cookie'] = 'cookie-string';
      return proxyReqOpts;
    }
  }));
}

app.listen(8000);

Comments:

  • For checking environment type I used construction process.env.NODE_ENV === 'production'
  • The best package for your requirements is express-http-proxy, but if you will need to proxy multiple endpoints, it will be painfully. Check http-proxy in this case.
like image 195
galkin Avatar answered Oct 14 '22 21:10

galkin