configure NodeJS process on two different machine - node.js

I have two different nodejs web app running on two different machine.
But I need to have one endpoint to user api1.abc.com/v1 to go one process and api2.abc.com/v2 go to another process.
how can i do this kind of request with the single endpoint to user (abc.com). need a nginx setup guide ?
I need this setup because internally I need to call user authenticated api from one server to another.

On one server you need to receive the data (using express & router):
router.get('/v1', function(req, res) {
// TODO
res.render('something');
});
and on the other you need to fetch:
var express = require('express');
var router = express.Router();
var app = express()
app.use('api1.abc.com', router);
router.post('/v1', function(req, res) {
// process res
});

You can write code at version two apis. In request you can pass version on which you need to call.
Call all api's on version 2. If it required to call on second server. Write code on version one to identify the call from version 2. So that it can by pass the basic authentication.
Thanks,

Related

What is the difference between "app.get/post/put/delete()" and "router.get/post/put/delete()"? [duplicate]

I'm starting with NodeJS and Express 4, and I'm a bit confused. I been reading the Express website, but can't see when to use a route handler or when to use express.Router.
As I could see, if I want to show a page or something when the user hits /show for example I should use:
var express = require('express')
var app = express()
app.get("/show", someFunction)
At the beginning, I thought this was old (for Express 3). Is that right or this is the way for Express 4 too?
If this is the way to do it in Express 4, what is express.Router used for?
I read almost the same example as above but using express.Router:
var express = require('express');
var router = express.Router();
router.get("/show", someFunction)
So, what's the difference between both examples?
Which one should I use if I just want to do a simple testing website?
app.js
var express = require('express'),
dogs = require('./routes/dogs'),
cats = require('./routes/cats'),
birds = require('./routes/birds');
var app = express();
app.use('/dogs', dogs);
app.use('/cats', cats);
app.use('/birds', birds);
app.listen(3000);
dogs.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('GET handler for /dogs route.');
});
router.post('/', function(req, res) {
res.send('POST handler for /dogs route.');
});
module.exports = router;
When var app = express() is called, an app object is returned. Think of this as the main app.
When var router = express.Router() is called, a slightly different mini app is returned. The idea behind the mini app is that each route in your app can become quite complicated, and you'd benefit from moving all that code into a separate file. Each file's router becomes a mini app, which has a very similar structure to the main app.
In the example above, the code for the /dogs route has been moved into its own file so it doesn't clutter up the main app. The code for /cats and /birds would be structured similarly in their own files. By separating this code into three mini apps, you can work on the logic for each one in isolation, and not worry about how it will affect the other two.
If you have code (middleware) that pertains to all three routes, you can put it in the main app, before the app.use(...) calls. If you have code (middleware) that pertains to just one of those routes, you can put it in the file for that route only.
Express 4.0 comes with the new Router. As mentioned on the site:
The express.Router class can be used to create modular mountable route
handlers. A Router instance is a complete middleware and routing
system; for this reason it is often referred to as a “mini-app”.
There is a good article at https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4 which describes the differences and what can be done with routers.
To summarize
With routers you can modularize your code more easily. You can use routers as:
Basic Routes: Home, About
Route Middleware to log requests to the console
Route with Parameters
Route Middleware for Parameters to validate specific parameters
Validates a parameter passed to a certain route
Note:
The app.router object, which was removed in Express 4, has made a comeback in Express 5. In the new version, it is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
How they are different
Everyone, including the documentation, tends to refer back to how much they are the same, but not actually reference any differences. Well, they are, in fact, different.
var bigApp = express();
var miniApp = express.Router();
listen()
The most obviously difference is that the bigApp will give listen, which just a rather confusing way to do what would otherwise be simple and obvious the node http or https module:
var server = require('http').createServer(bigApp);
server.listen(8080, function () {
console.info(server.address());
});
I consider this an anti-pattern because it abstracts and obscures away something that wasn't complicated or difficult in the first place, and then makes it difficult for people to use websockets and other middleware that require the raw http server.
Internal State
The big difference, which is really important, is that all bigApps have separate internal state.
bigApp.enable('trust proxy');
bigApp.enabled('trust proxy');
// true
var bigApp2 = express();
bigApp2.enabled('trust proxy');
// false
bigApp.use('/bunnies', bigApp2);
// WRONG! '/bunnies' will NOT trust proxies
A miniApp passed to a bigApp, however, will be operated by the bigApp in such a way that its internal state and thisness will be preserved and those routes will behave accordingly.
bigApp.enable('trust proxy');
bigApp.enabled('trust proxy');
// true
var miniApp = express.Router();
bigApp.use('/bunnies', miniApp);
// CORRECT! All state and such are preserved
This can be a big deal because express does a lot of (sometimes trixy) things to the http.ServerRequest and httpServerResponse object - such as modifying (or hijacking) req.url and req.originalUrl and various other properties you've been using without realizing - and you probably don't want that duplicated and separated.
Smaller API
There is a smaller, more well-defined number of functions a Router can use:
.use(mount, fn)
.all(mount, fn)
.options(mount, fn)
.head(mount, fn)
.get(mount, fn)
.post(mount, fn)
.patch(mount, fn)
.put(mount, fn)
.delete(mount, fn)
.route(mount).XXXX
.param(name, cb).XXXX
There are a few other convenience methods as well, such as basic(), but you won't find set() or enable() or other methods that change the larger app state.
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Post a random book')
})
As in above example, we can add different HTTP request method under a route.
Let’s say your application is little complex. So what we do first is we divide the application into multiple modules so that changes in one module doesn't clutter the others and you can keep working on individual modules, but at the end of the day you need to integrate everything into one since you are building a single application. It is like we have one main application and few child applications whose parent is the main application.
So when we create the parent application we create one using
const express = require("express");
const parent = express();
And to this parent application we need to bring in the child applications. But since the child applications are not totally different applications (since they run in the same context - java term), express provides the way to do it by means on the Express's Router function and this is what we do in the each child module file and lets call one such child module as aboutme.
const express = require("express");
export const router = express.Router();
By export we are making this module available for other to consume and since we have modularized things we need to make the module files available to the parent application by means of node's require function just like any other third party modules and the parent file looks something like this:
const express = require("express");
const parent = express();
const child = require("./aboutme");
After we make this child module available to the parent, we need to tell the parent application when to use this child application. Lets say when a user hits the path aboutme we need the child application about me to handle the request and we do it by using the Express's use method:
parent.use("/aboutme", child);
and in one shot the parent file looks like this:
const express = require("express");
const parent = express();
const child = require("./aboutme");
parent.use("/aboutme", child);
Above all what the parent can do is it can start a server where as the child cannot. Hope this clarifies. For more information you can always look at the source code which takes some time but it gives you a lot of information.
using app.js to write routes means that they are accessible to all the users as app.js is loaded on application start. However, putting routes in express.router() mini apps protect and restrict their accessibility.
In a word , express.Routercan do more things when compares to app.get(),such as middleware, moreover, you can define one more router object with express.Router()
express.Router has many options:
enable case sensitivity: /show route to not be the same as /Show, this behavior is disabled by default
strict routing mode: /show/ route to not the same as /show, this behavior is also disabled by default
we can add specific middleware/s to specific routes
In one of the questions in the quiz this was asked: "express.Router() creates an object that behaves similar to the app object."
The correct answer is 'True'. I know that we can both create routers by using either of the two but is it safe to say that they are not the same in all cases? If my understanding is correct, the express() variable can do more things like start a server while the other one cannot.
In a complicated application, app is module, for example article and user. router is controller or action in module, for example article create and list.
E.g the url https://example.com/article/create parse article module and create router.
also app and router can be level-in-level.

Node and Express – Conditionally Displaying Pages

What I want to do seems elementary; but, I am running into some blocks.
All I want to do is display pages based on a condition.
var express = require("express");
var app = express();
app.get('/', function(req, res) {
if (userIsLoggedIn()) {
res.sendFile(__dirname + '/public/index.html');
} else {
res.sendFile(__dirname + '/public/accessDenied.html');
}
});
I am looking to grab information from the browser – I want to call a function from another browserify-ed file, and use the return value to determine which page is displayed to the user.
I can't run the server from app.js because it needs to be browserify-ed since it requires Web3. And since the function relies on state, I am not sure how to access this state from the server file.
You have to post data from the browser to the server either with a form or query parameter.
For example:
web3.shh.post(object [, callback])
https://web3js.readthedocs.io/en/1.0/web3-shh.html#post
on the server site you need to extract those values and have to reply based on your posting.
How to process POST data in Node.js?
Unfortunately your use case is not clear ,but in general you might want to check out how to handle HTTP API communication.

Making and changing APIs when online in Nodejs

So were trying to develop an application (or Service) with Node.js that provides each user a custom API that can be called from {theirUserName}.ourwebsite.com. Users will be able to change/edit/remote the endpoints of the API within the application through our editor. They can add params to the endpoints, add auth, etc.
Now my question is, how can we make the API online at first, then how can we change the endpoints online without stopping the API application and running again?
P.S: APIs configuration will be saved into a JSON that will be saved to the DB and once the configuration change an event will be raised that tells us the endpoints have changed.
Using Express, you can add routes after the server is listening, so it's not a problem. Beware of precedence as it will be added at the bottom of the stack.
I would advise to have a db storing routes, and when running the node app (before listening) load all the routes in db and add them to the router. In order to be able to scale your app as well as being able to restart it safely.
Then start listening, and have a route for adding routes, deleting routes, updating routes etc.
Here is a simple example of adding a route after listening :
const app = require('express')();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const someGenericHandler = function(req, res) {
return res.json({ message: 'foobar' });
};
// it creates a route
app.post('/routes', function(req, res) {
try {
const route = req.body;
app[route.method](route.path, someGenericHandler);
return res.json({ message: `route '${route.method}${route.path}' added` });
} catch(err) {
return res.status(500).json({ message: err.message || 'an error occured while adding the route' });
}
});
app.listen(process.env.PORT);
You can try this code, paste it in a file, let say index.js.
Run npm i express body-parser, then PORT=8080 node index.js, then send a POST request to http:/localhost:8080/routes with a json payload (and the proper content-type header, use postman)
like this: { method: 'get', path:'/' } and then try your brand new route with a GET request # http://localhost:8080/'
Note that if you expect to have hundreds of users and thousands of requests per minute, I would strongly advise to have a single app per user and a main app for user registering and maybe spawn a small VPS per app with some automation scripts when a user register, or have some sort of request limit per user.
Hope this helps

Differences between express.Router and app.get?

I'm starting with NodeJS and Express 4, and I'm a bit confused. I been reading the Express website, but can't see when to use a route handler or when to use express.Router.
As I could see, if I want to show a page or something when the user hits /show for example I should use:
var express = require('express')
var app = express()
app.get("/show", someFunction)
At the beginning, I thought this was old (for Express 3). Is that right or this is the way for Express 4 too?
If this is the way to do it in Express 4, what is express.Router used for?
I read almost the same example as above but using express.Router:
var express = require('express');
var router = express.Router();
router.get("/show", someFunction)
So, what's the difference between both examples?
Which one should I use if I just want to do a simple testing website?
app.js
var express = require('express'),
dogs = require('./routes/dogs'),
cats = require('./routes/cats'),
birds = require('./routes/birds');
var app = express();
app.use('/dogs', dogs);
app.use('/cats', cats);
app.use('/birds', birds);
app.listen(3000);
dogs.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('GET handler for /dogs route.');
});
router.post('/', function(req, res) {
res.send('POST handler for /dogs route.');
});
module.exports = router;
When var app = express() is called, an app object is returned. Think of this as the main app.
When var router = express.Router() is called, a slightly different mini app is returned. The idea behind the mini app is that each route in your app can become quite complicated, and you'd benefit from moving all that code into a separate file. Each file's router becomes a mini app, which has a very similar structure to the main app.
In the example above, the code for the /dogs route has been moved into its own file so it doesn't clutter up the main app. The code for /cats and /birds would be structured similarly in their own files. By separating this code into three mini apps, you can work on the logic for each one in isolation, and not worry about how it will affect the other two.
If you have code (middleware) that pertains to all three routes, you can put it in the main app, before the app.use(...) calls. If you have code (middleware) that pertains to just one of those routes, you can put it in the file for that route only.
Express 4.0 comes with the new Router. As mentioned on the site:
The express.Router class can be used to create modular mountable route
handlers. A Router instance is a complete middleware and routing
system; for this reason it is often referred to as a “mini-app”.
There is a good article at https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4 which describes the differences and what can be done with routers.
To summarize
With routers you can modularize your code more easily. You can use routers as:
Basic Routes: Home, About
Route Middleware to log requests to the console
Route with Parameters
Route Middleware for Parameters to validate specific parameters
Validates a parameter passed to a certain route
Note:
The app.router object, which was removed in Express 4, has made a comeback in Express 5. In the new version, it is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
How they are different
Everyone, including the documentation, tends to refer back to how much they are the same, but not actually reference any differences. Well, they are, in fact, different.
var bigApp = express();
var miniApp = express.Router();
listen()
The most obviously difference is that the bigApp will give listen, which just a rather confusing way to do what would otherwise be simple and obvious the node http or https module:
var server = require('http').createServer(bigApp);
server.listen(8080, function () {
console.info(server.address());
});
I consider this an anti-pattern because it abstracts and obscures away something that wasn't complicated or difficult in the first place, and then makes it difficult for people to use websockets and other middleware that require the raw http server.
Internal State
The big difference, which is really important, is that all bigApps have separate internal state.
bigApp.enable('trust proxy');
bigApp.enabled('trust proxy');
// true
var bigApp2 = express();
bigApp2.enabled('trust proxy');
// false
bigApp.use('/bunnies', bigApp2);
// WRONG! '/bunnies' will NOT trust proxies
A miniApp passed to a bigApp, however, will be operated by the bigApp in such a way that its internal state and thisness will be preserved and those routes will behave accordingly.
bigApp.enable('trust proxy');
bigApp.enabled('trust proxy');
// true
var miniApp = express.Router();
bigApp.use('/bunnies', miniApp);
// CORRECT! All state and such are preserved
This can be a big deal because express does a lot of (sometimes trixy) things to the http.ServerRequest and httpServerResponse object - such as modifying (or hijacking) req.url and req.originalUrl and various other properties you've been using without realizing - and you probably don't want that duplicated and separated.
Smaller API
There is a smaller, more well-defined number of functions a Router can use:
.use(mount, fn)
.all(mount, fn)
.options(mount, fn)
.head(mount, fn)
.get(mount, fn)
.post(mount, fn)
.patch(mount, fn)
.put(mount, fn)
.delete(mount, fn)
.route(mount).XXXX
.param(name, cb).XXXX
There are a few other convenience methods as well, such as basic(), but you won't find set() or enable() or other methods that change the larger app state.
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Post a random book')
})
As in above example, we can add different HTTP request method under a route.
Let’s say your application is little complex. So what we do first is we divide the application into multiple modules so that changes in one module doesn't clutter the others and you can keep working on individual modules, but at the end of the day you need to integrate everything into one since you are building a single application. It is like we have one main application and few child applications whose parent is the main application.
So when we create the parent application we create one using
const express = require("express");
const parent = express();
And to this parent application we need to bring in the child applications. But since the child applications are not totally different applications (since they run in the same context - java term), express provides the way to do it by means on the Express's Router function and this is what we do in the each child module file and lets call one such child module as aboutme.
const express = require("express");
export const router = express.Router();
By export we are making this module available for other to consume and since we have modularized things we need to make the module files available to the parent application by means of node's require function just like any other third party modules and the parent file looks something like this:
const express = require("express");
const parent = express();
const child = require("./aboutme");
After we make this child module available to the parent, we need to tell the parent application when to use this child application. Lets say when a user hits the path aboutme we need the child application about me to handle the request and we do it by using the Express's use method:
parent.use("/aboutme", child);
and in one shot the parent file looks like this:
const express = require("express");
const parent = express();
const child = require("./aboutme");
parent.use("/aboutme", child);
Above all what the parent can do is it can start a server where as the child cannot. Hope this clarifies. For more information you can always look at the source code which takes some time but it gives you a lot of information.
using app.js to write routes means that they are accessible to all the users as app.js is loaded on application start. However, putting routes in express.router() mini apps protect and restrict their accessibility.
In a word , express.Routercan do more things when compares to app.get(),such as middleware, moreover, you can define one more router object with express.Router()
express.Router has many options:
enable case sensitivity: /show route to not be the same as /Show, this behavior is disabled by default
strict routing mode: /show/ route to not the same as /show, this behavior is also disabled by default
we can add specific middleware/s to specific routes
In one of the questions in the quiz this was asked: "express.Router() creates an object that behaves similar to the app object."
The correct answer is 'True'. I know that we can both create routers by using either of the two but is it safe to say that they are not the same in all cases? If my understanding is correct, the express() variable can do more things like start a server while the other one cannot.
In a complicated application, app is module, for example article and user. router is controller or action in module, for example article create and list.
E.g the url https://example.com/article/create parse article module and create router.
also app and router can be level-in-level.

Capture and log the api calls made to the server along with the passed data and the results

I have an api written in node.js that handles calls coming in from websites, desktop applications, iOS applications etc. There are probably 50+ endpoints and each end point can accept anywhere from 1 parameter to possibly 10-20 depending on what is intendeding to be accomplished. These can be GET/POST/PUT/DEL
I want to start load testing my API and simulating users activities.
What I am looking for is suggestions on how you can capture the API call and the parameters that were passed along with it in a logical way.
I use forever to run my app and everything is written to a log file so my initial reaction was to do something like add a piece of middleware to the express routes that would capture the endpoint as well as the req.params and req.body but then I need to put this middleware in all 50+ routes kind of tedious.
Anyone done something like this before and has a good idea on how to capture calls / data with those calls as well as possibly capturing what is returned from my API.
Perhaps some module?
I need to have this in a readable format to provide to other people so they can structure a fake set of calls... so raw log files aren't really helpful unless they are outputted.... "pretty".
Thanks!
You're on the right track – just add your logger middleware via app.use, which runs the middleware on every request (rather than adding it to each route).
In fact, the Express docs give an example of using logger middleware:
var express = require('express');
var app = express();
// simple logger
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
});
Connect (on which Express is built) provides logger middleware, so you can just do:
var logFile = fs.createWriteStream('./myLogFile.log', {flags: 'a'});
app.use(express.logger({stream: logFile}));

Resources