HomeContact
NodeJS
How to call a route internally using NodeJS
April 11, 2022
1 min

Let’s see how to call a route internally in a NodeJS application. You’ve just built several practical routes, like getting information on a user, but you want to use this method in another route of your NodeJS application. I will use Express for this example, but it works for all NodeJS frameworks (Fastify, Nest, etc.). If you have the error ECONNREFUSED and want to solve it, this article will show you how!

You have those routes and want to use common function between them:

var express = require('express');
var router = express.Router();

router.get('/api/user/:id', async function(req, res) {
    const {id} = req.params
    const user = await db.get(`users/${id}`) //this code depends of your database
    res.status(200).send(user)
});

router.put('/api/updateEventsUsers/:userId', function(req, res) {
    // I want to add user info in an event, I get only a userId, I want to update the event with more user information
});

In this case we have a NodeJS route that allow us to get all information of a user only with his ID. One thing we may want to do would be to request our route directly inside our NodeJS app :

router.put('/api/updateEventsUsers/:eventId/:userId', async function(req, res) {
    const { eventId, userId } = req.params
    const url = `https://localhost:3000/api/user/${userId}`;
    const user = await fetch(url)
    db.update(`events/${id}/users/${userId}`, user) //Again this line depend on your database, the logic is updating an event with user info.
    res.code(200).send({message: `Event ${eventId} successfully updated`})
});

This code will throw you the error ECONNREFUSED because you try to call a route inside your NodeJS app, and unfortunately, it’s not possible.

To solve that, we need to create a function that we will reuse across our NodeJS app for fetching user :

var express = require('express');
var router = express.Router();

const fetchUser = async (id) => {
  const user = await db.get(`users/${id}`)
  return user
}

router.get('/api/user/:id', async function(req, res) {
    const {id} = req.params
    const user = await fetchUser(id)
    res.status(200).send(user)
});

router.put('/api/updateEventsUsers/:userId', async function(req, res) {
    const { eventId, userId } = req.params
    const user = await fetchUser(userId)
    db.update(`events/${id}/users/${userId}`, user) // This line depends on your database
    res.code(200).send({message: `Event ${eventId} successfully updated`})
});

Instead of calling your internal route, you extrapolate the logic behind fetching a user in a function and make it reusable around your NodeJS app.


Tags

javascriptnodejs

Related Posts

How to automatically parse JSON stored in a string with NodeJS and Javascript.
April 07, 2022
1 min
© 2022, All Rights Reserved.

Quick Links

Contact Us

Social Media