Having trouble fetching JSON data from an Express server?

I successfully set up my first basic server using express, however I am encountering an issue when trying to fetch JSON data from a file called data.json:

Here is the code for the server:

const express = require('express')
const app = express()
const port = 5000

app.get('/data', (req, res) => res.send('data.json'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

The server.js file and the data folder containing the data.json file are located at the same level.

Although the server seems to be functioning properly, I keep receiving the error message Cannot GET /.

Can someone please help me identify what might be wrong with my code?

Answer №1

Based on the information provided, there are two primary issues that need to be addressed:

app.get('/data', (req, res) => res.send('data.json'))

needs to be updated to:

app.get('/data', (req, res) => res.sendFile('data/data.json'))

This is because the data.json file is located in the data folder and not at the same level as the server.js file.

The second issue lies with the route. The error message Cannot GET / appears because the only specified route is /data, meaning you can only make a get request from localhost:5000/data.

If you need further clarification or assistance, please let me know. https://expressjs.com/it/guide/routing.html

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

Utilize the Vue-Chartjs plugin registration for a specific chart component only

I am currently working with a chart component in Vue 3 using the composition API. My goal is to incorporate the datalabels plugin into this specific chart only. Upon attempting to register the plugin outside of the chart's data or options, I noticed ...

Tips for seamlessly creating the animation of sketching a line

Currently, I am working on a project that involves around 40 curved lines, each containing 30 to 200 points. Despite using BufferGeometry and setDrawRange() to draw all the lines equally, only the line with over 200 points appears smooth. I attempted using ...

The functionality of Express' render/redirect is limited to being triggered only by a submit method within a form

Objective To execute a POST request through a JavaScript method in order to send variable values as parameters. Setup NodeJS Express BodyParser ejs Initial Approach Frontend: <html> <head> <script src='http://ajax.go ...

Exploring the Power of Pythons, Selenium, and XPATH for Handling New Windows

Is it possible to retrieve an element through XPath after using the .click() method when that element is located within a section of JavaScript known as BODY_BLOCK_JQUERY_REFLOW and appears only after the click action? I am attempting to access this speci ...

Unable to convert the value "undefined" to an ObjectId (type string) in the "_id" path for the "Order" model

As someone who is new to Javascript and working on an e-commerce website, I am currently facing a challenge with displaying the order id on the return page. Each time I try to do so, I encounter an error message that reads Cast to ObjectId failed for val ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

Is Handlebars indicating that it requires missing assistance?

Attempting to manually render a handlebars template on the server side using Express. //require handlebars var hbs = require('hbs').create({ svg: require('handlebars-helper-svg'), switch: require('../helpers/switch.js'), ...

The versions of my npm and node are not compatible, despite using nvm

I have recently started working with node and npm. I need to run a program repository for my job, which requires compatibility with node version 10.13.0 or even 8.11. I attempted to install nvm, but now every time I try to execute any npm command (includ ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...

Execute asynchronous functions without pausing the thread using the await keyword

When working with an express route, I need to track a user's database access without: waiting for the process to complete before executing the user's task worrying about whether the logging operation was successful or not I'm uncertain if ...

JavaScript sorted arrays are an efficient way to keep data

In my dataset, I have an array of objects representing various products. Each product object includes a field called ratingReviews and another field called price, which can either be a string or an object. If the price is represented as an object, it conta ...

Pass the input value through ajax without utilizing the val() function

Here is my scenario: I have multiple input fields: <label class="minilabel">Field1</label><input type="text"> ... <label class="minilabel">FieldN </label><input type="text"> I need to extract the value of each input f ...

AngularJS refrains from computing expressions

As a newcomer to AngularJS, I decided to experiment with some basic code. However, the results were not as expected. Here is the HTML code that I used: <!DOCTYPE html> <html ng-app> <head> <script src="js/angular.min.js"></sc ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

What advantages does $sce or Strict Contextual Escaping provide in AngularJS, and why is it unnecessary for React?

I find it perplexing that I am unable to fully grasp the true value of utilizing SCE in AngularJS (even after reviewing the documentation) when it comes to security benefits. It leaves me wondering why React does not require SCE. So, to summarize my quest ...

What is the best way to combine an additional array into a different project attribute?

There are 2 arrays being used. This is the content of userGroups: console.log(this.items) [ { "id": 63, "name": "URLGROUP-1643836551908" } ] The contents of urls are shown below: userGroup can contain ...

Retrieve a dynamic HTML object ID using jQuery within Angular

In my Angular application, I have implemented three accordions on a single page. Each accordion loads a component view containing a dynamically generated table. As a result, there are three tables displayed on the page - one for each accordion section. Abo ...

Changing the size of circles in text and adjusting the dimensions of SVG elements

As a novice JavaScript programmer, I am attempting to resize circles and SVG elements based on the window size. Currently, my code creates circles of varying sizes, but I haven't been able to adjust them in relation to text size. var width = 600; va ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

Tips for pairing MongoDB queries across fields

Imagine having a set of data: { id: 0, likes: 1}, { id: 1, likes: 0}, // ^ indicating a match { id: 2, likes: 0}, { id: 3, likes: 0} *The 'likes' column refers to the matching 'id'. For example, id:0 matches with id:1 because id:0 lik ...