The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files?

  • file1.js
  • file2.js

The code inside file1.js is as follows:

var express = require('express');
var app = express();
app.get('/foo/bar1', (req, res) => res.json(['bar1'])

Can I follow the same approach for file2.js but with a different endpoint?

var express = require('express');
var app = express();
app.get('/foo/bar2', (req, res) => res.json(['bar2'])

Will this setup pose any potential issues with express?

Answer №1

To avoid initiating express twice, it is recommended to separate the endpoints handlers into different files and then import them. Here's an example:

// handler1.js
modules.exports = function handler1(req, res) {
  // do something here
}


// handler2.js
modules.exports = function handler2(req, res) {
  // do something here
}


// app.js
const express = require('express');
const handler1 = require('./handler1');
const handler2 = require('./handler2');

const app = express();

app.get('/foo/bar1', handler1);
app.get('/foo/bar2', handler2);

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

Sending PDF file to client's request using PDFKIT and Strapi (Koa) via HTTP response

My goal is to send a PDF file as a response to a GET request on my Strapi endpoint. The current Strapi controller, which uses Koa, is structured like this: const PDFDocument = require("pdfkit"); module.exports = { async printOne(ctx) { const doc = ...

Error message '[object Error]' is being returned by jQuery ajax

I'm currently facing a challenge with my HTML page that calls an API. Every time I attempt to run it, I encounter an [object Error] message. Below is the code snippet in question: jQuery.support.cors = true; jQuery.ajax({ type: "POST", url: ...

Swapping the icon in the panel heading of Bootstrap 3 Collapse based on its collapse status

Despite many attempts, I haven't been able to make any of the provided answers work in my code. My setup involves using Bootstrap 3 panels and collapse functionality to display advertisements. In the default view, only the advertisement heading is vi ...

The best method for sending JSON or JS objects along with Form Data using AJAX POST to PHP for optimal efficiency

Although it may seem like a repetitive question at first glance, I have carefully gone through all related posts and have not come across a clear answer or solution to my specific issue. Any guidance towards relevant material would be greatly appreciated, ...

What is the best way to bring a JavaScript file from the source file into an index.html document

I am currently in the process of developing a system using React, and as someone new to the framework, I have encountered an issue. I need to include a JavaScript file in my index.html that is located within the src folder. This js file is essential for th ...

Executing a function on each page within the head tag in Nuxt.js

I successfully made my function accessible by using the plugin attribute in the nuxt.config.js file, allowing me to call the function under mounted on every page. I am looking for a more efficient way to run this function within the head tag and have it b ...

Module.exports causing keyword errors in eslint

Encountering some unusual errors from eslint CI regarding my jest.config.js file. 1:1 error Rule 'no-empty-label' has been replaced by: no-labels no-empty-label 1:1 error Rule 'no-reserved-keys' has been replaced ...

Can JavaScript impact the appearance of the printed version of a website?

Just a quick question - I currently don't have access to a printer. My client is wondering if the hidden elements of the webpage (items that are only visible when clicked on) will be included when printing or if they will remain hidden? ...

Struggling to understand the process of retrieving information from an Axios promise

For my current project, I've been experimenting with using Axios to retrieve JSON data from a json-server to simulate a database environment. While I can successfully display the retrieved data within the .then() block of the Axios function, I'm ...

Retrieving a single post from a JSON file using AngularJS

I'm currently delving into AngularJS, but I seem to be stuck on what might be a simple issue. At the moment, I have some hardcoded JSON files with a few persons in them and no actual backend set up yet. In my form, I aim to display a single person ea ...

Updating field based on dropdown value in CakePHP 3.6.11

I have the following tables: customers[id, name, surname, phone, text, balance, created] service_types[id, title, price, length, is_subscription, created] customer_service_types[id, customer_id, service_type_id, price, created] Within the add.ctp file o ...

Validation of default values in contact forms

Obtained a free contact form online and hoping it works flawlessly, but struggling with validation for fields like "Full Name" in JS and PHP. Here is the HTML code: <input type="text" name="contactname" id="contactname" class="required" role="inpu ...

How can we verify that console.log has been called with a specific subset of expected values using Jest?

I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions: //utils.js export const util_sum = ( ...

Developing an interactive Breadcrumb component using Vue.js in the latest version, Vue 3

Struggling to develop a dynamic Breadcrumb-Component in Vue.js 3. After hours of research, I haven't found a suitable solution due to outdated methods or lack of flexibility. As a beginner in frontend development, I am unsure about the best library to ...

The React.js Mui Collapse component exclusively triggers animation during the transition while closing, without any animation when expanding

Whenever I implement the Collapse component from Mui library in my projects, I face an issue where the transition animation only works when closing the component (when in={false}). However, when opening the component, there is a delay before the animation ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

Utilizing AngularJS filter method to populate data

Just beginning my journey with Angular js, I've got this snippet of code that is responsible for binding data to the div element, app.filter("myfilter", function () { return function (data, catName) { if (angular.isArray(data) && angular ...

Using Node.js to send a photo through a Telegram Bot

I've been trying to send a photo via node.js using this function, but it's not working. telegram-bot-api https://www.npmjs.com/package/telegram-bot-api var telegram = require('telegram-bot-api'); var api = new telegram({ token: & ...

Node.js may not always save Winston log files when using process.exit()

I'm struggling to grasp a particular concept... when I use process.exit() in a program that logs events to both the console and a file, all the log events are displayed on the console as expected, but only the first one (or none at all) is actually sa ...