Jeff
Jeff

Reputation: 221

Node, Express API Gateway

I'm trying to create a simple API gateway type project that takes in incoming routes and redirects them to other external apis. I'm trying to have an incoming route of /test go to google.com or any other API with some req.body but I don't think I am doing it right.

var app = express();    
app.get('/test', function(req, res){
var options = {
    host: 'www.google.com',
    port: 80,
    path: '/index.html'
};

var req = http.get(options, function(res) {
    console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

I'm trying the http.get / post but I can't put them inside the app.get function?

Upvotes: 2

Views: 4376

Answers (3)

Serhii Kuts
Serhii Kuts

Reputation: 449

Using Express.js proxying can be done fairly easy using http-proxy lib:

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

var apiProxy = httpProxy.createProxyServer();

app.get("/*", function(req, res){ 
  apiProxy.web(req, res, { target: 'http://google.com' });
});

Another variant is to use config based approach with express-gateway library

Install globally npm i -g express-gateway
execute eg gateway create to create sample project

inside created directory open config/gateway.config.yml file and paste the following config:

http:
  port: 8080
apiEndpoints:
  api:
    host: localhost
    paths: '/*'
serviceEndpoints:
  google:
    url: 'https://google.com'
policies:
  - proxy
pipelines:
  - name: default
    apiEndpoints:
      - api
    policies:
      - proxy:
          - action:
              serviceEndpoint: google 
              changeOrigin: true

Here is getting started guide: http://www.express-gateway.io/getting-started/

Upvotes: 2

hyprstack
hyprstack

Reputation: 4228

I now this answer comes rather late, but if you are using Expressjs in conjunction with api-gateway, there is a new module, aws-serverless-express that can be used to port your Express app onto Api-Gateway. You can find a tutorial here!

If what you want is to just redirect users, then simply change your code to use res.redirect('www.google.com');, as Lucas mentioned in his answer.

var app = express();    
app.get('/test', function(req, res) {
    res.redirect('www.google.com');
};

If what you want, first get data from another API and then display that to the user, I would suggest using the request module, which is battle tested and makes your code look cleaner. On the other hand, using nodejs's core http module does make your code "lighter".

With the request module you would have

var app = express(); 
var request = require('request');   
app.get('/test', function(req, res) {
    var options = {
        method: 'GET',
        url: 'www.google.com',
    }
    request(options, function(err, response, body) {
        if (err) {
            return res.status(500).end();
        }
        res.send(body); // send whatever you want here
    });
};

Upvotes: 1

Lucas Watson
Lucas Watson

Reputation: 803

Right now you're trying to define the variable req, however the problem here is that this variable represents the request that the server (this code) received. Since its already been sent and captured by the server, you can't change it, this is what the client sent to you.

If I understand you correctly, you want this server to act as a sort of central "API proxy", where it receives requests, and responds with data from various other APIs.

So we can't do anything with req, but we can respond to the client with res. To do this, create an http.get request similar to the one you have, capture the data from this, and then in the callback, use res.send(data);

Take a look at the Express docs, they're very helpful. As well, if you're simply trying to redirect the client to another page, there's res.redirect, which is very useful. http://expressjs.com/en/api.html#res.redirect

Edit: Here's an example of what I'm talking about Edit 2: Fixed pseudo code to real code that runs

app.get('/test', function(req, rootRes){
  var options = {
    host: 'jsonplaceholder.typicode.com',
    port: 80,
    path: '/users'
  };

  http.get(options, function(res) {
    console.log("Got response: " + res.statusCode);

    var theData = '';
    res.on('data', function(body){
      theData += body;
    });

    res.on('end',function(){
      console.log(theData);
      if(res.statusCode < 399) {
        rootRes.send(200,theData); //send a success code with the data
      }else{
        rootRes.send(res.statusCode); //send the client whatever error the server experienced
      }
    });
  }).on('error', function(e) {
  console.log("Got error: " + e.message);
  rootRes.send(501); //internal server error
  });
});

Note that I wrote this in 2 minutes, so take this as pseudo code that may not run. Also, look up docs on handling status codes and proper practice.

Upvotes: 0

Related Questions