Encountering difficulties in retrieving JSON data from an Express server by utilizing the Fetch API

My Express server is running on port 8080 and I have the following middleware set up:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

When trying to make a request from port 8081 using fetch, I encounter an error:

fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))

The error message states:

Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Oddly enough, when I manually enter the Express URL in the browser, I am able to see the JSON I am trying to fetch.

Despite reading several posts on resolving this issue, I am still unable to find a solution.

How can I adjust my fetch request to avoid this CORS error?

Answer №1

The reason for the CORS error message is due to fetching data from a different port, specifically port 8081. To resolve this issue, you will need to adjust the Access Control policy by using the following code:

  res.header("Access-Control-Allow-Origin", "http://localhost:*");

For additional information on this topic, you can refer to this useful link.

Answer №2

Eliminate this issue by utilizing the `cors` package:

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())

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

Attempting to invoke a promise within a function yields an error message stating that it lacks call signatures

Recently, I came across this interesting class: export class ExponentialBackoffUtils { public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) { function waitFor(milliseconds: number) { return new Pr ...

Open a fresh window using Javascript and add new content inside

After creating a script that opens a window and writes content when the button is clicked once, I noticed that clicking the button again causes the window to gain focus instead of rewriting the content. Does anyone have any ideas on how to fix this issue ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...

Unraveling the onsubmit FormObject in an HTML form within the Google Sheets Sidebar: Tips and tricks

In the sidebar, I am setting up a form with 27 inputs to create new sheets based on various criteria. The form includes a text entry field and multiple groups of radio buttons and checkboxes. However, I am currently facing an issue when trying to create a ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...

How to prevent the collapse action when clicking a button inside a div in Bootstrap 5 using data-bs-toggle

My div contains a data-bs-toggle attribute along with buttons. https://i.sstatic.net/RzagX.png When clicking on the panel, it collapses. However, I do not want this collapse event to trigger when clicking the buttons. Is there a way to control this behav ...

Tips for Formatting Your Schema Correctly

Currently, I am working with nextjs and trying to display the Schema inside the head tag. However, when I do so, it displays &quot;:&quot; instead of my intended content. This is the schema code snippet: const Schema = (url,image) => ( < ...

Combine an array nested within an object with each key of the object

Alright, let's dive into the structure of these objects: custom_fields:{ 21:{ edit:true required:true show:true } } In my Angular controller, this object is stored under $scope.page.custom_fields. Within this object, there is another ...

Retrieve a value from a different collection in MongoDb

Is it possible to copy certain fields from one collection to another? I am looking to copy the values of 'bar' to the 'foo' collection, excluding the 'type' field. Additionally, I want to add a new _id and an extra field (use ...

Setting the height of the Angular UI modal relative to the height of the window

I am currently working on a modal that contains a significant amount of text. My main goal is to limit the height of the modal to the size of the window, while also adding a scrollbar to the content area positioned above the OK button. Check out the Plunk ...

The collection of users is not being successfully sent to the view template

I have a successfully functioning route similar to this: // Dashboard route router.get('/dashboard', ensureAuthenticated, (req, res) => { Note.find({user: req.user.id}) .then(notes => { res.render(' ...

How can I implement JQuery in JavaScript to enhance functionality on an HTML webpage?

I'm currently working on a website project and I'm running into some trouble with my jQuery library. I've tried implementing the code below, but it doesn't seem to be working. I'm using Notepad++ with Denwer local server. <scrip ...

The session storage system does not retain any user data

I am currently working on developing REST APIs using Express, MongoJS, and Connect-Mongo. I'm facing an issue with storing data in sessions: var express = require('express'), mongojs = require("mongojs"), MongoStore = require('connect ...

Display the div only during the printing process

Imagine I have a situation where there is a block of content that I only want to show when printing. It looks something like this: <div id="printOnly"> <b>Title</b> <p> Printing content </p> </div&g ...

Tips for incorporating animation while altering element styles within JavaScript

I am looking to incorporate a sliding animation that moves the element downward when the display property is set to block, and upward when it's set to none or an empty string, here is the current JavaScript code I have: <script> function showQ ...

Unable to locate module within a subdirectory in typescript

The issue I'm facing involves the module arrayGenerator.ts which is located in a subfolder. It works perfectly fine with other modules like Array.ts in the parent folder. However, when I introduced a new module called Sorting.ts, it started giving me ...

Emails not being sent by Nodemailer

I recently configured my glitch project with a contact form and I'm attempting to set it up so that it sends me an email when someone fills out the form. The issue I'm experiencing is that while the server console logs indicate that the message h ...

I noticed that my jquery code is injecting extra white space into my HTML5 video

Ensuring my HTML5 background video stays centred, full-screen, and aligned properly has been made possible with this jQuery snippet. $(document).ready(function() { var $win = $(window), $video = $('#full-video'), $videoWrapper = $video. ...

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...