Send a res.json response and retrieve it using res.render in a different router

Trying to retrieve a JSON from the route "/api/product" and display it using hbs on the "/product" route. The code seems to be working, but is it done correctly?

The router in this case is: '/api/product'

router.get('/', this.controller.renderProducts);

renderProducts = async (req, res) => {
    try {
      const docs = await this.ProductsDAO.getAll();

      const products = docs.map((p) => {
        return new ProductDTO(
          p.id,
          p.price,
          p.stock
        );
      });

      res.status(200).json({ product:products });
    } catch (error) {
      logger.error('Error rendering products', error);
      res.status(400).send('Failed to render products');
    }
  };

Should I add this code to server.js for it to work properly?

app.get('/product', new RequestViews().getAllProducts)

class RequestViews {
  constructor() {
    this.url = 'http://localhost:8080/api/product';
  }

 getAllProducts = (req, res, next) => {
    request.get(this.url, (err, response, body) => {
      if (err) {
        return next(err);
      }
      res.render('products', JSON.parse(body));
    });
  }

Thank you!

Answer №1

Minimize internal HTTP requests in your Express app by consolidating logic into reusable functions.

One approach is to encapsulate mostrarTodos() and .map() within a function...

const retrieveProducts = async () => {
  const data = await ProductsDAO.mostrarTodos();

  const products = data.map((p) => new ProductDTO(p.id, p.price, p.stock));
};

and utilize this function across route handlers

displayProducts = async (req, res) => {
  try {
    res.status(200).json({ products: await retrieveProducts() });
  } catch (error) {
    logger.error("Error rendering products", error);
    res.status(400).send("Failed to render products");
  }
};
class RequestViews {
  showAllProducts = (req, res, next) => {
    retrieveProducts()
      .then((products) => {
        res.render("products", { products });
      })
      .catch(next);
  };
}

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

Mastering the art of customizing classes and styles in material-ui (React)

I am facing a challenge with version 1.2.1 of material-ui. My goal is to make the AppBar component transparent by overriding its styles as per the documentation here. This is the code snippet I have been working on: import React, { Component } from ' ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

The only thing you can see in MongoDB output is the objectid

Trying to save data in mongodb using an open schema. After making a post request, the only thing showing up in the database is the objectid. As someone new to MongoDB and Node.js, I'm struggling to identify where my mistake lies. // <---------se ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

How can one easily implement a countdown timer in an Ionic 3 app?

Easily create an Ionic3 timer set to 2 minutes that displays countdown like 1:59, 1:58, and finally reaches 00:00. Once the timer hits 00:00, a block of HTML content will be shown. ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Creating a hierarchical tree structure from tabular data with JavaScript ECMAScript 6

Seeking a JavaScript algorithm utilizing ECMAScript 6 features to efficiently convert JSON table data into a JSON tree structure. This approach should not employ the traditional recursive algorithm with ES5, but rather emphasize a functional programming me ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

What is the best way to obtain the current cursor location in draft.js?

As part of my draftjs project, I'm working on implementing a feature that allows users to easily insert links. One approach I've taken is creating a popup that appears when the shortcut cmk + k is pressed. To enhance the user experience, I am cu ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

AngularJS and numerous parallel indexed tables side by side

I need help with displaying two tables, one for profiles and the other for rates. The rates are connected to profiles through the rate name in the JSON data. Is there a way to show these two tables side by side? And when a row is selected in the profile ta ...

Trouble arises when the properties of this.props are supposed to exist, yet they are not

Wow, what a name. I am struggling to come up with a better title given my current state. The problem at hand is as follows: When using React, I set the state to null during componentWillMount. This state is then updated after data is fetched from a serve ...

DataTables.js, the powerful JavaScript library for creating interactive tables, and its compatible counterpart

I'm currently making some changes to a dynamic table that require enabling a vertical scroll bar. As a result, I need to implement this vertical scroll bar mechanism on an existing table. The code in our project utilizes dataTables.js version 1.5.2 ...

Error: Undefined object while trying to access 'injection' property

After updating to React 16.x, I encountered the following error: Uncaught TypeError: Cannot read property 'injection' of undefined at injectTapEventPlugin (injectTapEventPlugin.js:23) at eval (index.js:53) at Object.<anonymous> ...

What's going on with the background color? It doesn't seem

I have incorporated Bootstrap into my html code and I am attempting to modify the background color of a div when the screen resolution changes from large to medium or small. Even though I have added a class, the change does not reflect when adjusting the ...

Correct Way to Use 'useState' in Formik's 'onSubmit' Function?

I recently encountered an issue while using Formik in my Next.js application. Specifically, I am facing a problem with the submit `Button` component, which accepts a `showSpinner` prop to control its behavior. When set to true, the button is disabled and d ...

PHP: A guide on validating textboxes with jQuery AJAX

How can I use jQuery AJAX to validate a textbox on focusout? The validation process includes: Sending the value to a PHP page for server-side validation Displaying an alert message based on the validation result I have only impl ...