I encountered a 'CORS policy restriction' while attempting to perform a redirect using expressJS

I encountered an issue while attempting to redirect with ExpressJS. I implemented a login system that processes a post request, and if the user exists, the page is supposed to redirect. However, Cors seems to be blocking the redirection.

Here is the code snippet for the request:

router.post('/login', async (req, res) => {

    try{    
       let usersData = await  getFiles(__dirname + '/users.json');
       let parsedUsers = JSON.parse(usersData);
       let userChecker;
       for(let i = 0; i < parsedUsers.length; i++){
       if(parsedUsers[i].userName === req.body.userName){
           userChecker = 1;
           break;
       } 
       }

       if(!userChecker){
        console.log(`${req.body.userName} does not exist`);}
        else {
        console.log(`${req.body.userName} Approved`);
        res.redirect('/')
       }
        }
     catch (err) {
      if(err) throw err
    };
})

This is the error message displayed in the console:

Access to fetch at 'http://localhost:3001/users/login' (redirected from 'http://localhost:4000/users/login') from origin 'null' 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.

Could someone shed some light on what might be causing this CORS problem?

Answer №1

In order for the browser to allow access, you must send specific headers from the server indicating the permitted domain. You can achieve this by implementing a
Manual header

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
    next();
});

// your code
router.post('/login', async (req, res) => {

});

Cors npm module:

//to install the cors module, run this command
npm install cors // install the cors

// use it in your code
app.use(cors()) // will enable cors

// your code
router.post('/login', async (req, res) => {

});

Answer №2

The reason behind this issue is that CORS (Cross-Origin Resource Sharing) is currently not permitted in your project. To resolve this, you can incorporate the cors package.

npm install cors

Following the installation, execute the following steps:

app.use(cors()) // This will handle all CORS requests

With these simple actions, you will be all set to proceed. Implementing cors in this manner is the easiest solution.

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

Issue with sending variable from Axios to API endpoint in React

I am currently working on an Express/React application (not yet ready for production) that allows users to withdraw a specific amount of money from the database. On the withdrawal page, I have multiple buttons all marked as submit buttons. These buttons c ...

Angular's ng-for directive allows for easy iteration over a collection of

I have a list of links that I am looping through using the ng-for directive. Each link is supposed to display an icon with different timing intervals thanks to a plugin called wowjs. The first link should appear quickly, while the last one should appear sl ...

"Troubleshooting 3D Models not appearing correctly in Mapbox when using Three.js

My issue lies in the inability to load any .gltf file, only a standard one. For further details, please continue reading. The map on my application showcases a 3D model indicated by the red arrow: https://i.sstatic.net/3Ce09.png The model is a GLTF file ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

NPM packages installed on a global level are not being detected

Recently, I experienced a system crash that led me to delete some files in an attempt to fix the issue. Among those files may have been ~/.profile. Since restoring my system, I've noticed that my globally installed npm packages are no longer functioni ...

Why is my PHP function not able to properly receive the array that was sent to it via Ajax?

After retrieving an array through an ajax query, I am looking to pass it to a PHP function for manipulation and utilization of the elements at each index. The PHP function in question is as follows: class ControladorCompraEfectivoYTarjeta { public fu ...

Tips on utilizing the getElementsByClassName method in JavaScript

Check out this HTML snippet: <html> <body> <div id="wrapper"> <div id="c_wrapper"> <div class="member"> <form name="f1"> </form> </div> ...

Fetching data from a list separated by commas using Firebase database

Is there a way to store comma separated ids on a child node in Firebase and filter data similar to using the IN clause in SQL? If so, I would appreciate suggestions for possible solutions. ...

Tips for updating the Google Map Key from a JAVASCRIPT script in DJANGO using a personalized variable

Is there a way to securely hide my Google Map API key in the JavaScript code? The key is dynamically generated from Django settings. I am uncertain about the proper implementation using JavaScript and src. settings.py GOOGLE_MAP = "XZZZZZZX" v ...

Is there a tool available that can convert a cron schedule into a more user-friendly, easy-to-read format?

My search for an NPM package that can handle this task has been fruitless so far. I am in need of a cron library that can convert a monthly cron job into easily readable text. For example, inputting 0 0 14 * * should output "Monthly", rather than the curre ...

Connect chosen options from Multicombobox in personalized UI5 control

I am looking to connect selectedItems, which are sourced from JsonModel in the controller, to a custom control. Custom control sap.ui.define([ 'sap/ui/core/Control', 'sap/m/MultiComboBox', ], function (Control, MultiComboBox) { ...

Difficulties involving AJAX requests in Firefox and Internet Explorer

My checkbox triggers an AJAX request whenever its state changes (checked/unchecked). Everything was working fine when I tested in Chrome. But when I tried using Firefox or IE, the AJAX request wasn't updating the value in the SQL server. I'm a b ...

Finding an element that appears after a JavaScript script has run and is visible on the page

<div class="inline-check"> span class="ic-check" style="display: inline;"> I am currently facing a challenge in locating the HTML code snippet provided above. This snippet represents a text box that accepts numbers and displays a green check mark ...

What is the time complexity for finding a specific value in a two-dimensional matrix?

The challenge at hand is quite straightforward: develop an algorithm that can determine if the target value exists within the given matrix. Here, I have devised two potential solutions. However, I am uncertain as to which one would be more efficient. Perso ...

Utilizing the jQuery Selector for Headers

I am currently working on grasping the concept of using the Jquery selector. https://learn.jquery.com/using-jquery-core/selecting-elements/ In my project, I have a table and I am trying to create an input field within a modal. My main challenge lies in c ...

Adjusting window scrolling on iPad/iPhone based on orientation

When the page loads, I am automatically directing the user's scroll to the top of the '#gallery-view' element. This behavior functions correctly on iPad and iPhone. However, if the device orientation is changed, the positioning does not wor ...

I encountered an issue where the variables in my environment files were returning as undefined when I tried to access

After creating my Vue application using vue/cli with the command vue create my-vue, I decided to build the project in next mode. Following the steps outlined in the Vue documentation, I created a .env.next file at the root of the project with the following ...

Running onSubmit function during render in React using Firebase

Currently, I am working on setting up a document within a collection in Firebase Firestore. To achieve this, I have developed a component that renders a div containing a button, which conditionally displays a FormValidation (a form) based on the 'ope ...

Utilizing Radio Buttons for Table Selection in a React Application

Currently, I am utilizing React, MUI, and Formik in my project. My task involves implementing a table where only one radio button can be selected per row. How can I achieve this functionality? If you want to take a look at my code, it's available on ...

What is the ideal solution for resolving the problem of loading HTML page content in this specific situation?

Currently, I am working on an HTML website project where I am integrating header and footer content from separate HTML files into each page using jQuery. However, I have encountered an issue while the page is loading. Upon loading, the content initially ...