Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node.

index.js

import express from 'express';
import bodyParser from 'body-parser';
import usersRoutes from './routes/users.js';

const app = express();
const PORT = 5000;

app.use(bodyParser.json());

app.use('/users', usersRoutes);

app.get('/', (req, res) => {
    res.send('hello');
});

app.listen(PORT, () => console.log(`Server running on port: http://localhost:${PORT}`));

user.js

import express from 'express';
const router = express.Router();


router.get('/', (res, req) => {
    res.send();
});

export default router;

https://i.stack.imgur.com/wDiDt.jpg

Answer №1

import express from 'express';
import userData from '../user.json' // < ------- updated path
const router = express.Router();


router.get('/', (res, req) => {
    res.send();
});

export default router;

Answer №2

To ensure compatibility with the version you are using, you may need to utilize babel or add the --experimental-json-modules flag for the module to function properly. It's worth noting that node v.14 does not require any additional steps.

Try running: node --experimental-json-modules about.js

import express from 'express';
import userfile from '../user.json' // import the json file
const router = express.Router();

router.get('/', (res, req) => {
    res.send(userfile);  //this line sends the json
});

export default router;

Answer №3

Consider utilizing the filesystem module:

const userData = require('fs').readFileSync('../userData.json', 'utf-8');

Answer №4

Here is a simple way to achieve it:

import express from 'express';
import user from '../user'; // <---- No need for the .json extension here.
const router = express.Router();


router.get('/', (res, req) => {
    res.send(user);
});

export default router;

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

Ways to position cursor at the end in the Froala Editor

My current dilemma involves the need to position the focus/cursor at the end of text that is loaded within the Froala editor. I attempted to accomplish this using the focus event of Froala (events.focus), but unfortunately, it did not yield the desired out ...

Uploading files using node.js with the help of express, multer, fast-csv

Currently, I am attempting to implement a file upload functionality using pug, multer, and express. The structure of the pug form used for uploading a file is as follows: form(method='POST' enctype="multipart/form-data") div.form-group ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

How can I create a dynamic height for a scrollable div?

How can I build a section with a defined height that contains a sticky header (with a dynamic height) and a scrollable body? I want the body to be scrollable, but due to the header's changing height, I'm unable to set an exact height. What should ...

Refreshing a Next.js page results in a 404 error

I've set up a Next.js page called page.js that can be accessed through the URL http://localhost:3000/page. However, I have a need to access this page through a different URL, namely http://localhost:3000/my-page. To achieve this, I decided to utilize ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Is it true that AFNetworking stores cookies generated on the server indefinitely?

Having an issue with my iOS application. I am using AFNetworking to communicate with my REST api on a node.js server (powered by express.js). I have two endpoints - one for logging in and another for logging out. When a user logs in, I create a cookie on ...

Issue: Attempting to send a POST request to the specified API endpoint for creating a product category resulted in a 500 Internal Server Error

My current task involves inserting data into a table using the POST method with an Angular service function. angular.module("productCategoryModule") .factory("productCategoryService",productCategoryService); productCategoryService.$inject = ['$http& ...

error: local server did not return any data

I am currently using PHP on a Linux machine. In my HTML code, I have set up an AJAX request to the local Apache server (check http://localhost), with the intention of displaying the data from the server on the screen. However, for some reason, nothing is b ...

What is the process by which node.js synchronously delivers a response to a REST web service?

Sorry if this question seems obvious! I'm struggling to grasp how node.js handles requests from the browser. I've looked at tutorials online where express.js was used to create the server-side code with node.js. Routes were then set up using prom ...

Tips for effectively structuring express routes

Struggling to understand how to effectively utilize the /:variable notation. My current setup includes this layout: router.route("/").get() router.route("/:id").get().put().post().delete() router.route("/auth").get().put().pos ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

The PrimeNG FullCalendar feature seems to be malfunctioning and cannot be located

I've been working on integrating a FullCalendar module into my Angular 7 project. Despite following the steps provided in this link, I haven't had any luck: After executing this command: npm install <a href="/cdn-cgi/l/email-protection" clas ...

tips for configuring scripts with npm, babel, and commanderjs

Can anyone assist me in understanding why I am facing difficulties retrieving the option '-x' (mentioned below)? Do I need to escape certain characters? Furthermore: why does this command work: node b.js parse url1 url2 url3 -x but this one d ...

Unveiling the Truth about Svelte Transitions

Recently, I attempted to incorporate the guidance provided in this repl () for implementing flying and fading effects on divs. However, it seems that I may have a slight misunderstanding regarding the concept... To tackle this, I designed a component rese ...

No response from jQuery's $.getJSON() function

I'm currently experimenting with jQuery by using a script that I wrote. As a beginner in learning jQuery, I am trying to read data from a .json file and display it in a div. function jQuerytest() { $.getJSON( "books/testbook/pageIndex.json", func ...

Issue with posting a form in react-router-dom action()

Having trouble with sending form data to the backend? The backend works fine with Postman, but not with the frontend. Here's a look at my code: Below is the code for App.js: import { RouterProvider, createBrowserRouter } from "react-router-dom&q ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

What methods are available to modify the colors in an Apex bar chart?

Currently, I am in the process of constructing a bar chart using react, mui, and apex-chart. One specific requirement I have is to modify the colors of the bars displayed on the chart. Despite my efforts in attempting various solutions, I have been unsucce ...