Development is hindered due to Cors policy restricting access to the localhost webapp

Currently, I am working on developing a web application and an API simultaneously, but I'm facing some issues with CORS blocking. This concept is relatively new to me, and I'm eager to improve my understanding.

Firstly, I have set up an Express server for the API:

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

module.exports = app.post('/posttest/', cors(), async (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.json({ msg: 'Successfully tested with CORS!' })
})

This server is running locally on http://localhost:3000 The "posttest" mentioned above refers to the module that handles my route.

const posttest = require('./src/routes/posttest.js')
const server = require('http').createServer();
const { Router } = require('express');

server
  .on(
    'request',
    Router({ mergeParams: true })
    .use( posttest )
  )
  .on('listening', () =>{
    console.log('listening');
  })
  .on('error', () => {
    console.log('ERROR!!!!');
  })
  .listen(3000);

Next, in my web application, I make a POST request using fetch:

fetch('http://localhost:3000/posttest/', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({text:'test'}),
    mode: 'cors' }) .then( (res) => {   //resolve }) .catch( (err) => {   //error    });

It's worth mentioning that the web app is served locally on localhost:8080

The issue arises when attempting to make a post request as it results in the following error:

Error: Access to fetch at 'http://localhost:3000/posttest/' from origin 'http://localhost:8080' 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.

I primarily use Chrome for development. Any suggestions on why this is happening? I was under the impression that including

res.header('Access-Control-Allow-Origin', '*');
would resolve the issue. Interestingly, Postman can access the route successfully. However, when accessing the same route through a browser, it gets denied. The same problem persists during production deployment. Can someone provide a simple explanation, perhaps suitable for a five-year-old?

Thank you in advance for your assistance.

Answer №1

A pre-flight request, also known as an OPTIONS request, is essential for CORS handling. If your cors() handler is currently only set up for POST requests through .post, you can globally disable CORS by adding the following code:

  app.use(cors());

If you want to enable pre-flight requests for a specific route, you can do so by using the folllowing code:

  app.options("/posttest/", cors());
  app.post('/posttest/', cors(), async (req, res, next) => {  
   res.json({ msg: 'Enabling CORS for this route!' });
  });

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

Creating glitchy dotted lines in an HTML Canvas with the help of translate and scale techniques

I'm working on creating a canvas where users can draw symmetrical lines with their mouse. However, when I use the transform and scale attributes in the draw function to achieve this effect, it creates small gaps in the line and makes it look less smoo ...

Conditionally displaying ng-options in AngularJSI'm looking for a

After spending hours searching, I'm unable to find a solution to my problem. I was able to implement it before but lost the code and can't remember how I did it. I need to display only certain array values in a select box using ng-options. The d ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

Guide to connecting two geometric shapes together with the help of three.js

Is there a way to link two spheres together with a line? I'm looking for a solution that mimics two balls connected by a rope or something elastic. Does anyone have any examples to share? ...

Issue encountered when attempting to utilize renderToString in React.js for server-side rendering with express framework

This is the content of my server/server.js file: import express from "express"; import React from "react"; import ReactDOMServer, { renderToString } from 'react-dom/server'; import App from '../src/App'; const POR ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

Tips for importing and exporting icons in a way that allows for dynamic importing using a string parameter

I am facing an issue with dynamically importing SVG icons in React Native. Initially, I tried using the following code snippet: const icon = require(`@src/assets/icons/${iconName}`) However, after realizing that this approach wouldn't work for me, I ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...

Attempting to deploy my node.js application on Heroku resulted in an error message saying that the web process failed to bind to $PORT within 60 seconds of launch, causing the process to exit with status

I recently encountered an issue while attempting to deploy my node.js app on Heroku. The error message stated that the Web process failed to bind to $PORT within 60 seconds of launch, and the Process exited with status 137. I'm unsure of how to resolv ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

Navigate to a precise point in a video using react hooks in videojs

I am currently working on adding a feature that allows users to skip forward or backward by 15 seconds in a video. However, I am encountering difficulties when it comes to updating and setting the current time accordingly. const videoNode = useRef(null); ...

Creating a stunning image carousel in Vue by integrating a photo API: step-by-step guide

Trying to figure out how to create an image carousel in Vue using photos from an API. Currently able to display the photos using: <section class="images"> <img v-for="image in images" :key="image.id":src="image.assets.large.url"> &l ...

Achieving synchronous function execution with a single click in React

In my current project, I am utilizing ReactJs and Redux. I have encountered a scenario where I need to trigger two functions sequentially with just one click on the mainfunc(). The second function should only execute after the first function has complete ...

The algorithm for editing multiple phone numbers

I'm working on a form for my project that requires saving 4 phone numbers. The text boxes for entering the phone numbers are revealed on button clicks. Here's what I need to implement: When adding entries---> Enter the first phone number. C ...

Unable to load local image file for texture in Three.js

When attempting to utilize a local image for loadTexture in Three.js, I encountered the following error: Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at .... may not be loade ...

Issue encountered: Document not being saved by Mongoose, error message received: "MongoClient connection must be established"

Currently, I am attempting to establish a connection with MongoDb using mongoose. Below is the code snippet that I have implemented for this purpose: controller.js const conn = mongoose.createConnection(db, { useNewUrlParser: true, ...

Exploring ways to showcase informational alerts when a link is hovered over by the mouse

I am currently working on a website that showcases links utilized by my team. One specific requirement is that when a user hovers over a link, note information should be displayed. Although the simplest solution would be to not list the link if it's n ...

Tips for Navigating and Scrolling to an Element by its ID in a Next.js Page Enhanced with AnimatePresence

Currently, I am utilizing Framer Motion to add animations to the page transitions in a Next.js project. However, when implementing AnimatePresence, it seems to interfere with the navigation to specific elements using hash links (id). The seamless transitio ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...