Async action on server results in fetch request being canceled

Having an existing fetch request:

fetch(`http://localhost:4000/test`, {
  method: 'GET',
  mode: 'cors',
  cache: 'no-cache',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(result => console.log('success'))
.catch(error => console.log('error', error));

Also, implementing a nodejs express router (express-promise-router) for the same request:

this.router.get('/test', (request: Request, response: Response) => {
  response.status(200).send({'status': 'ok'});
});

Initially, the fetch request succeeds without any issues. However, upon changing the nodejs router function to be async:

this.router.get('/test', (request: Request, response: Response) => {
  return asyncFunction().then(result => response.status(200).send({'status': 'ok'}));
});

An error occurs where the fetch is cancelled and TypeError: Failed to fetch is displayed in the console.

Interestingly, accessing the /test API through the browser URL or Postman results in success. The cause of the fetch failure remains elusive, even after attempting the same operation with Axios.

Answer №1

My initial assumption about the problem being related to the fetch was incorrect. It turned out that the issue was actually caused by the event in which the fetch function was being called. To resolve the issue, I included an event.preventDefault() at the end of the method to stop the event and ensure that the fetch operation was executed correctly.

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

Tips for saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

Is it feasible to utilize Google Calendar API for JavaScript through npm install? Alternatively, can the Google Calendar API be utilized for Node.js in the browser within Next.js?

Looking to integrate the Google Calendar API as a library in your Next.js project without using _document.tsx? I have explored two potential approaches for achieving this: Utilize the google calendar api for JavaScript by installing it via npm Use the goo ...

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...

When the location path is not set to /, the Node.js application fails to load

There seems to be an issue with my Node.js app running on 127.0.0.1:8081 where it requires /. If I set it up like this, both / and /projectb can successfully load the page. server { listen 80; location / { proxy_pass http ...

Develop an error handler in Express.js to manage all error scenarios efficiently

I have implemented an errorMiddleware class in my Nodejs API : const { appLogger } = require('../utils/logger'); const { getENVValue } = require('../utils/fonction'); const CustomException = require('../utils/CustomException') ...

ExpressJS/Jade: Struggling with Recaptcha formatting problem

I have successfully integrated recaptcha into my ExpressJS app, but I am facing an issue with the formatting as it is including extra '<'s and '>'s. I followed the instructions provided at this link: https://www.npmjs.org/package/re-cap ...

What is the best way to set up configurations and execute a particular npm script depending on the chosen option?

I need help figuring out how to set up options and execute an npm script based on the selected option in the terminal. For instance, I have a package.json file: { "scripts": { "tests:mac": "export ENV=dev& testcafe \& ...

The electron shell window mysteriously closes by itself after a period of time

Just a simple Hello World application built with electron-prebuilt is up and running. I start it using the command npm start. The window pops up as expected, but unexpectedly closes after some time. Before the window closes, these warnings are displayed ...

I have encountered a roadblock in my app as a result of implementing Google Strategy with PassportJs in

Recently, I created an application using the MERN stack and implemented PassportJs for user authentication. I utilized the Google strategy for authentication purposes; however, I encountered some issues. Upon reviewing the console, I found the following e ...

Starting up a Sails.js application in Webstorm for debugging seems to be quite time-consuming

While developing a project in Sails using the Webstorm IDE for debugging purposes, I've encountered an issue. As I add more controllers, models, and features to the app, the load time increases significantly when in debug mode. Normally, the app takes ...

Having trouble loading static files in Pug even though the static file directory has been configured in Express.js

Currently, as I work on developing my application, I am faced with a challenge in sending an email using Pug as the template engine. The issue lies in loading static files within my template. While my code effectively designates the public folder of the pr ...

Guide to Retrieving 'req' in JavaScript within Node.js / Express Framework

I have a loaded page named tournament/:key, where a Tournament object is passed. The Jade template accesses variables from the Tournament using syntax like #{tournamentData.name} to display the data on the page. The list of matches is stored as an array wi ...

Automate the execution of webdriver/selenium tests when a form is submitted

I am currently faced with a challenge in setting up an application that will automate some basic predefined tests to eliminate manual testing from our workflow. The concept is to input a URL via a user-friendly form, which will then execute various tests ...

To initialize SocketIO on the client-side, you must provide the server URI when calling io()

As a beginner in React, I am currently working on a simple React web application using Nodejs/Express for Universal rendering and incorporating socket.io for real-time data updates. While going through the documentation for socket.io, I came across the re ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

What's the reason for this express server operating on dual ports?

Here's a simple node server setup I have: const express = require('express'); const request = require('request'); const apiServerHost = "http://<IP address>:3000/api#!/" const app = express(); app.use('/', fun ...

Utilize the nodeclipse extension for enhanced functionality

Recently, I started using the Nodeclipse plugin in Eclipse to work with NodeJS and ExpressJS. However, when I created an ExpressJS project and tried to run the app.js file, I encountered the following error message: /home/ali/node_modules/express/lib/expr ...

Experiencing difficulties sending AJAX requests to an Express server while utilizing React Router

I am encountering difficulties with making ajax requests to fetch data from a MongoDB database. The application is coded using React, utilizing React-Router for routing and running on an Express server. The ajax calls are being handled using whatwg-fetch. ...

Encountering a 404 error when using Vue history mode in conjunction with an Express

I'm facing an issue with my Vue SPA hosted on an Express server. Whenever I use history mode and refresh the page, I encounter a 404 not found exception. I attempted to solve this problem by utilizing the connect-history-api-fallback package but unfor ...

Troubleshooting the Node.js Server Error Encountered when Enabling AngularJS html5Mode(true)

When using routeProvider and stateProvider in AngularJS with HTML5 mode set to true, everything functions correctly until the page is refreshed. On a Node.js server, I am unsure of what needs to be written on the server side to prevent receiving a "Can no ...