Express proxy cookie API calls

I use express where I made fun of the API calls for my application.

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

Below is an example of 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 launch my application in the local API from my code, " http: // localhost: 3000 / brand " should be redirected to " http://www-dev.abc.com/brand "

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

Is there a proxy server that I can use? Could you give some examples?

+5
source share
1 answer

If you understand correctly, then your list of requirements is as follows:

  • Easy integration with express .
  • A proxy is only one endpoint.
  • Proxies only in the local environment.
  • Ability to set cookies for proxy 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

  • To check the type of environment, I used the construction process.env.NODE_ENV === 'production'
  • The best package for your requirements is express-http-proxy , but if you need to proxy multiple endpoints, it will be painful. In this case, check the http-proxy .
+1
source

Source: https://habr.com/ru/post/1274154/


All Articles