Encountering CORS issue despite employing a CORS library

Encountering a CORS error while attempting to deploy my project on render using expressjs and react. The project functions smoothly on localhost, but changing the URLs to match the website results in this error:

Access to XMLHttpRequest at 'https://book-listing-app-api.onrender.com/login' from origin 'https://book-listing-app.onrender.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Despite manually adding the header in the request and trying fetch instead of axios to rule out default configuration issues, I still face some form of blocked-by-CORS error.

function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [redirect, setRedirect] = useState(false);

  async function loginUser(e) {
    e.preventDefault();

    try {
      const response = await axios.post(
        `${process.env.REACT_APP_SERVER_URL}/login`,
        {
          username: username,
          password: password,
        },
        {
          withCredentials: true,
          // headers: {
          //   "Access-Control-Allow-Origin": "https://book-listing-app.onrender.com",
          // },
        }
      );
      // const response = await fetch(
      //   `${process.env.REACT_APP_SERVER_URL}/login`,
      //   {
      //     method: "POST",
      //     headers: { "Content-Type": "application/json"},
      //     body: JSON.stringify({
      //       username: username,
      //       password: password,
      //     }),
      //     credentials: 'include'
      //   }
      // );
      if (response.status === 200) {
        setRedirect(true);
      }
    } catch (err) {
      if (err.response.status === 401) {
        alert("Invalid username or password");
      }
    }
  }

Have also attempted to add more options in the cors configuration on the backend and setting the header manually in the '/login' method using res.set().. both of which lead to a blocked-by-CORS error.

const cors = require('cors');

app.use(
  cors({
    credentials: true,
    origin: 'https://book-listing-app.onrender.com',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['content-type', 'Authorization', 'token'],
  }),
);
// app.options('/login', cors());
app.post('/login', (req, res) => {
  try {
    const { username, password } = req.body;
    console.log(username, password);

    if (!username || !password) {
      return res
        .status(400)
        .json({ error: 'Username and password are required' });
    }

    const q = 'SELECT * FROM book_store.users WHERE username = ?';

    db.query(q, [username], (err, data) => {
      console.log('Query Error:', err);
      console.log('Query Result:', data);
      if (err) {
        console.log(data);
      }

      if (data.length === 1) {
        const { id, username, password: storedPass } = data[0];
        console.log('Entered password:', password);
        console.log('Stored hashed password:', storedPass);
        const passMatch = bcrypt.compareSync(password, storedPass);
        if (passMatch) {
          jwt.sign(
            {
              id,
              username,
            },
            secret,
            {
              expiresIn: '1h',
            },
            (err, token) => {
              if (err) {
                console.log(err);
              } else {
                // res.set('Access-Control-Allow-Origin', 'https://book-listing-app.onrender.com');
                res.cookie('token', token).json({ id, username });
              }
            },
          );
        }
      } else {
        res.status(401).json({ error: 'Invalid username or password' });
      }
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: 'Internal server error' });
  }
});

Moreover, contacted render and they clarified that their site does not affect CORS in any way, revealing that the issue lies within the code. To confirm this, tried hosting it on azure and encountered the same CORS error.

Answer №1

To ensure proper CORS handling, the CORS header must be present in the server response and not the request. The purpose of CORS is to allow the server to control which origin domains are permitted to access its data (for compliant browsers).

For example, when a request is made to from the origin , CORS rules come into play.

The server's response should include the header

Access-Control-Allow-Origin: https://book-listing-app.onrender.com
to authorize cross-origin requests specifically from the domain book-listing-app.onrender.com.

Additional Access-Control-* headers may be necessary depending on the requirements of the cross-origin request.

Access-Control-Allow-Methods: <HTTP METHOD>
restricts the CORS request to certain HTTP methods, with GET, PUT, POST, DELETE, HEAD being the defaults.

Access-Control-Allow-Credentials: <boolean>
determines whether cookies should be included in the request or not.

Browsers are becoming more stringent when it comes to enforcing CORS policies. It is crucial that the exact protocol://domain:port is specified in the CORS Access-Control-Allow-Origin header returned by for enhanced security measures.

  • Understanding CORS and Access-Control-Allow-Headers

  • Resolving CORS Issues on Chrome

  • Troubleshooting CORS Problems on Chrome

  • Investigating CORS Failure on http://localhost

  • Enabling CORS on localhost

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

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

Having trouble setting up email with Passport-local. Any new suggestions?

I have been working on implementing user log-in using passport-local and express. While I have successfully managed to achieve log-ins with usernames, I find them hard to remember and not ideal for user authentication. Therefore, I attempted to customize t ...

Collaborative API with Individual Sessions

Currently, I have two React apps running on different localhost ports; app A on localhost:4000 and app B on localhost:3000. I have successfully configured CORS to allow app B to send requests to app A with credentials enabled. However, I am facing an issu ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

Google Assistant - Linking accounts using Google Sign-In

I have integrated Google authentication and authorization via passport into my Express app. Recently, I started working on integrating it with Google Assistant, following the guidelines at https://developers.google.com/actions/identity/google-sign-in#start ...

Conceal the div if it remains unhidden within the following 10 seconds

This piece of code is designed to show a loader image until the page finishes loading. Here is the code snippet: document.onreadystatechange = function () { var state = document.readyState if (state == 'interactive') { $('#unti ...

AJAX/PHP causing delays due to lag problems

I've been trying to implement an asynchronous call in my PHP script, but I keep running into the same issue: "Maximum call stack size exceeded." This is causing severe lag on my site and I suspect there might be a loop somewhere in my code that I just ...

Display different text based on the property value

I need to display different text based on the value of a property, showing "offline" if camera.key is null and "online" otherwise. Here's the template I'm using: <h3>Camera sensors</h3> <table> <th>Name</th> ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

How can we activate navigation on a mobile browser?

I am currently working on a small HTML5/JavaScript website designed to be accessed by mobile browsers on devices such as Android and iPhone. I am utilizing the geolocation feature of HTML5 to obtain the user's current location, but my goal is to then ...

Encountering a Node.js error when executing the JavaScript file

When I try to run my Node.js application using the command "node main.js" in the terminal, I encounter an error saying "Error: Cannot find module 'D:\nodeP\main.js'". This is confusing for me as I have set the environment variable path ...

The flat function for JavaScript Arrays is not defined in React Native

I am currently developing an application using react-native and it's common knowledge that we can utilize JavaScript code in this particular project as well as any other react projects. However, whenever I attempt to use the following code snippet, t ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

How can you resize a circle in Three.js without resizing its outline?

I'm currently using a THREE.Path to generate a Circular path and then utilizing a TubeGeometry to form a circle with transparent fill and an adjustable stroke thickness. My main query revolves around the process of scaling up the Circular path dynamic ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

Encountering a Node.js error while using ssh2: ECONNRESET read error

I have been attempting to utilize npm's ssh2 package to establish an SSH connection and remotely access a machine. The code functions properly for connections from Windows to Linux/MacOS, but encounters issues when connecting from Windows to Windows ( ...

Refreshing the request object in socket.io

Is there a way to update the socket.request.session.passport object in Node.js using an Ajax request? I attempted reconnecting the sockets after an Ajax call, but it didn't work. It appears that this object on the server is only updated upon page rel ...

Tips for displaying JSON data in HTML without the use of placeholder DIV elements

Customer Scenario: A user wants to search through Wikipedia. The search results should be limited to 5 articles, and the user should be able to view the title and introduction of each article. Developer Scenario: User input is provided via an HTML input f ...

Issue with Browsersync causing task to malfunction in Gulp 4

Gulp Local v4.0.2, CLI v2.3.0 Browsersync v2.26.13 gulpfile.js: 'use strict' const gulp = require('gulp') const concat = require('gulp-concat') const babel = require('gulp-babel') const uglify ...

Issue encountered while attempting to launch server using Node.js and Express

I am relatively new to backend development and encountered an issue yesterday while attempting to run my server. Here is the snippet of code where the error occurs: const express = require("express"); const app = express(); PORT = 8443; app.listen("POR ...