Unable to fetch JSON file from the local server

I'm trying to develop a server API using Koa. This server will have a single API endpoint, /api/data, which should read a local json file and display its content in the browser when a user accesses localhost:3000/api/data.

const Koa = require('koa');
const serve = require('koa-static');
const Router = require('koa-router');
// const http = require('http');
const fs = require('fs');

const app = new Koa();
const router = new Router();

app.use(serve('.'));

router.get('/api/data', async (ctx, next) => {
  await fs.readFile('./data.json','utf-8', (err, data) => {
    ctx.body = JSON.parse(data);
  });
});

app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);

Unfortunately, I'm encountering an error with a status code of 404. Since I am relatively new to Koa, I'm not sure where I'm going wrong. Could someone please assist me with this issue?

Answer №1

When using <code>fs.readFile, it does not return a promise, causing koa not to wait for it to finish. Consequently, if the body is still empty at the end of your middleware function, you will receive a 404 page.

To address this issue, you must either promisify all your asynchronous functions or utilize their synchronous counterparts.

Your middleware should be structured like this:

router.get('/api/data', async (ctx) => {
    // Make sure to specify utf8, as fs.readFileSync returns a buffer otherwise
    let data = fs.readFileSync('./data.json', 'utf8')
    ctx.body = JSON.parse(data);
})

Answer №2

If you need to access that file, streaming it might be a more efficient option:

router.get('/api/data', async (ctx, next) => {
  var readStream = fs.createReadStream('./data.json','utf8');
  ctx.body = readStream;
  await next();
});

Instead of using await fs.readFile(), consider using ctx.body to send out the data directly.

LATEST UPDATE

It is recommended to remove app.use(serve('.')); and place this middleware after the router middlewares:

app
  .use(router.routes())
  .use(router.allowedMethods())
  .use(serve('.'));

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

There has been an issue processing the request body. TypeError has occurred because the 'builtin_function_or_method' object is not iterable in this context

I am new to programming and this code is not mine, it's for a course. I encountered an error while trying to call an API to analyze a photo. The issue seems to be in this line: response =requests.post(address, headers=headers, params=parameters, data= ...

Looking for mouseover tooltips in three.js?

Currently, I am working on loading an object similar to this demo. My goal is to display a tooltip or infobox when hovering over a specific part of the object. For example, upon clicking the top button, I would like a tooltip to appear above the box. I hav ...

I'm encountering a persistent issue of receiving null when attempting to read a JSON object file in

Every time I attempt to read, the result is always null. This pertains to a json file. { "team": { "name": "john 1", "id": "12345" } } I am attempting to accomplish this using POJO. public class Team { private String name; private ...

What is causing the disparity between the JSON generated using the `Factory` and the one received from the `API`?

When I use my mock stub, the escaping works properly, but with the API response, the escaping does not seem to be applied for some reason. Here is a snippet of my Mock stub factory. require 'faker' F ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

Passing properties to delete items

When I click on the button, I want both the icon and the button to disappear. I've attempted a solution but it's not working correctly. Any help would be greatly appreciated. const Button = (props) => { const[toggleIcon, setToggleIcon]=React ...

Getting image links from JSON in Flutter using regex

Hello, I am new to Flutter and I have been working on developing a note-taking app using flutter_quill. As I was saving the data into JSON format, I encountered the following data: [{"insert":"Ttttttt\n"},{"insert":{"image":"/data/user/0/com.example. ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

Refresh the Google Maps location using GPS coordinates

Currently, I am working with an Arduino that has a GPS chip and processing NMEA strings with Python. I have an HTML file set to auto-refresh every x seconds to update the marker's position. However, I would like to update the position information with ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

Having trouble with my loop using Jquery's $.get method

Having an issue with Jquery mobile / JavaScript I'm struggling to properly loop through the different values of data in my "get" function, where it should be sending ...cmd=PC&data=06464ff ...cmd=PC&data=16464ff ...cmd=PC&data=26464ff ...

Is there a way to implement form validation without causing a page refresh?

My attempts to implement mobile number validation using jQuery on a submit button without page refresh have been unsuccessful. The validation only works when the page is refreshed after clicking the submit button. Below is the code I've been using: ...

Encountering an Issue with jQuery 1.9.1 when Checking the #idCheckbox in Internet Explorer Versions 7 and 8

Currently, I am utilizing jQuery version 1.9.1 and my code is functioning smoothly on IE9, Firefox, and Chrome. However, the issue arises when trying to make it work on IE7 and IE8, where it fails to execute. In my setup, there is an input checkbox with t ...

The user's input is not being bound properly when using $scope.$watch

Just started my Angular journey and I've been stuck for the past couple of days trying to figure out how to bind data from a new search using a service. Previously, I had the search functionality working with the code below before transitioning to a s ...

Why do certain URLs bypass the filters despite not meeting the criteria in the Chrome extension?

I am currently developing a Chrome extension that is designed to automatically close tabs when specific URLs are visited, helping me stay focused and avoid distractions. The list of sites that should trigger tab closures includes: YouTube Facebook Reddit ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

Moving the panel to follow the mouse cursor in Firefox Add-on SDK

Is there a way to show a panel on the screen at the exact position of the mouse? I'm finding it difficult to understand how to change the position of the panel in Firefox SDK, as the documentation lacks detailed information. ...

Guide on how to clear and upload personalized information to Stormpath

After receiving JSON data from my client, I am looking to store it in Stormpath's custom data using node.js with express.js: I have set up a basic post route: app.post('/post', stormpath.loginRequired, function(req, res){ var data = req.b ...

Is there a way to ensure a dialog box is positioned in the center of the window?

After adjusting the dimensions of my jQuery UI dialog box with the following code: height: $(window).height(), width: $(window).width(), I noticed that it is no longer centered on the window. Do you have any suggestions on how I can recenter it? ...