Generating an internal express request

Is there a way to initiate an internal request in express without the full process of a real request? Here's an example to illustrate the idea:

app.get("/pages/:page", funciton(req, res)
{
    database_get(req.params.page, function(result)
    {
        // This route requires fetching additional data through another request:
        request(result.user_href, function(user_response)
        {
            result.user = user.response.json;
            res.send(result);
        });
    });
});

/// ....

app.get("/user/:name", function() ... );

Essentially, I'm looking for a simpler way to access this data without duplicating routes and having to rebuild logic. Any suggestions on how to achieve this more efficiently?

Answer №1

Is it possible to bypass the need for an actual request? Unfortunately, no. If you require the href from the initial request to access a user object, then you must proceed with a second "real request."

However, if you have a database containing user information, there is a way to avoid this request by including the user's ID on the page and simply making a standard database call instead of following the href.

Here's a demonstration of refactoring code to separate logic:

// Minimize logic in routes:
app.get('/page/:page', function(req, res){
  var pageId = req.params.page;
  makePage(pageId, function(err, result){
    if(err){ return res.send(500) }
    res.send(result)
  }) 
})

// Abstract complex functions:
function makePage(pageId, callback){
  database_get(pageId, function(result) {
    // The second request becomes necessary at this stage
    getUserByHref(result.user_href, function(err, data){
      if(err){return callback(err)};
      result.user = data.json;
      callback(null, result);
    });
  });
}

// Abstract repetitive actions:
function getUserByHref(href, callback){
  request(href, function(err, response, body){
    if(response.statusCode != 200){
      return callback(err);
    }
    var user = JSON.parse(body);
    return callback(null, user);
  })
}

// If local users existed, abstract the database call using getUserById
function getUserById(id, callback){
  db.fetch(id, function(err, data){
    return callback(err, data);
  })
}

Answer №2

I have created a specialized middleware specifically for this purpose using the uest library. You can find more information about it in my comprehensive response available here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Chrome-exclusive: Dealing with Overflow in Twitter Bootstrap Form Inputs

I've encountered a strange issue where datetime-local inputs exceed their boundaries on Chrome (tested on Chrome 35 x64 for Linux), but not on Firefox (29.0). Here's a screenshot demonstrating the problem in Chrome: chrome screenshot And here&a ...

Jasmine secretly observes the behavior of Angular services

I'm currently in the process of setting up unit tests for an angular controller using jasmine and karma. Due to the length of my code, I won't be able to include it all here. However, I'll provide some snippets: CompilerController.js (the c ...

Retrieving & Refreshing Data with ajax and Jquery

I have been working on developing a forum system using jQuery, PHP, Bootstrap, and other technologies. The forum allows users to post, delete, and edit their posts. I have implemented an edit button for the author of the post, which triggers a modal wind ...

Fluctuating and locked header problem occurring in material table (using react window + react window infinite loader)

After implementing an Infinite scrolling table using react-window and material UI, I have encountered some issues that need to be addressed: The header does not stick to the top despite having the appropriate styles applied (stickyHeader prop). The header ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

By comparing two JSON arrays and using the matches found, create a third JSON array

In a specific scenario, I am required to compare two JSON arrays to check if their name fields match each other. If the name fields match, then I need to create a third JSON array. For example: Let's consider the first JSON array as [{"name":"hx ind ...

When working with VueJS and Vuex, using the splice method to replace an item (object) in an array stored in Vuex does not trigger a re-render of the

I have an array of records. Each record consists of an object with _id (mongo id), title, and value (value is an object with amount and currency). When displaying the list of records using v-for, the ':key' for each item in the list is set to th ...

What is the best way to verify a form in Vue?

I'm trying to create a registration form in Vue and using v-form from Vuetify and vue-property-decorator. However, the usual method of triggering validation with this.$refs.form.validate() is not working for this specific form. How can I trigger the ...

Setting up validation with yup based on the value of a CheckBox component can be achieved by following these

I am currently working with a validationSchema const validationSchema = Yup.object().shape({ first_name: Yup.string().required("First Name is required"), last_name: Yup.string().required("Last name is required"), email: Yup.string().required( ...

Using Bootstrap for Fixed Headers and Section Anchors

Despite my best efforts, I am struggling to resolve an issue with my fixed bootstrap navbar and internal links. I have experimented with various solutions, including using a JavaScript onscroll event listener and applying styles directly in the markup. How ...

Transferring an array to the server-side with the help of $.getJSON

Utilizing $.getJSON() function to send data to the server side (PHP, Codeigniter) in the form of an array and using the returned data for further processing. Issue: Sending an associative array to the server does not yield any results on the server side. ...

Discover how to extract the value from the server side during document.ready using jQuery without the need for any specific event

In my project, I'm facing a requirement where I need to fetch a value from server-side code using any event and utilize it to create a dialog box. Initially, I attempted to retrieve the value in window.onload but discovered that window.onload is trigg ...

What are some ways to enhance the content within a JWT?

After following this tutorial, I am interested in adding additional information to the token. Specifically, I would like to include an 'accessRights' field that can be used for user authorization in both the backend and Angular. Where should I i ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

Can the rgb color selection feature be utilized in the $mdThemingProvider?

Currently, I am in the process of developing a Firefox OS application using angularjs and angular-material. One feature that I would like to incorporate is allowing users to customize the colors of their app. To achieve this, I have utilized the md-slider ...

A method for utilizing wildcards in conjunction with the .load function

Currently, I am utilizing jquery, jquery mobile, js, html, and css within Phonegap to develop my android/ios application. However, my understanding of js & jquery is somewhat limited. In my index.html file, I use .load to load other html files into s ...

By implementing JavaScript formulas into a CSV file for importing into Google Sheets, the outcome is the creation of numerous columns

I have been struggling to insert the following formula into a single column in Google Sheets using JavaScript, but it keeps appearing in different columns due to the presence of commas. =IF(A2="VALID", B2, 0) Currently, I am utilizing the code ...

What is the best way to extract the JSON value from my API website and assign it to a new variable

Currently, I am in need of a way to convert a username into an ID. To accomplish this task, I will utilize the following API link: (where "username" is replaced by the variable name.) The main objective here is to extract the ID value from the provided li ...

Receiving a SyntaxError in Node.js with the message "Unexpected token *" while attempting to import

node: v10.16.3 npm: 6.12.0 Encountered an error while trying to import express in node. Referencing the code from https://github.com/angular-university/rxjs-course, specifically server/server.ts. To run server.ts, used the following command: $ ts-node ...

Using html data attributes to encode JSON data with strings

Looking for a way to pass data to JavaScript, I decided to create a template tag as shown below: from django.utils.safestring import mark_safe from django import template import json register = template.Library() @register.simple_tag def mydata(): r ...