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

My Angular JS http.get request is failing to reach the specified URL

While working with AngularJS to integrate RESTful web services into my website, I am encountering an issue where I am consistently receiving errors instead of successful responses. I have been stuck on this for the past three days and any assistance would ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

Is there a more "Angular-esque" approach to implementing this (inter-element communication)?

I have created a custom directive that will automatically add an asterisk to the label of any input field marked as required. The following is my link function with detailed comments: // This is what the DOM structure looks like: // <label id="label-1" ...

Having trouble installing handlebars on Node using the command line

I've been attempting to integrate handlebars with node using the instructions from my book. The guide advised me to install handlebars like so: npm install --save express3-handlebar. However, this resulted in an error npm WARN deprecated express3-han ...

Updating a component from a different source

As a newcomer to React, I'm curious about the ability to update one component's content based on events from another component. I have two React components set up. The first component loads data when the page initializes, while the second compon ...

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

Issue with Webstorm not automatically updating changes made to JavaScript files

On my HTML page, I have included references to several JavaScript files such as: <script type="text/javascript" src="MyClass.js"></script> When debugging in WebStorm using a Python SimpleHTTPServer on Windows with Chrome, I am able to set bre ...

unable to retrieve the city name through geographical location information

I am currently using the following code snippet to retrieve the country and city names: <?php $user_ip= getenv('REMOTE_ADDR'); $geo= unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); $city= $geo["ge ...

Implementing a Unique Approach to Showcase the Initial PDF Page as Cover through Django and JS

I would like to enhance my script so that when a user hovers over an object on the template, a PDF cover page can be set for each object. Current process: Currently, I am able to upload files in the .pdf and .epub formats for each object with additional ...

Any suggestions on how to secure my socket connection following user authentication in redux?

After onSubmit, userAction.login is called which then dispatches "SUCCESS_AUTHENTICATE" to set the token of the user and socket state in their respective reducers. How can I proceed to trigger socket.emit("authenticate", {token})? ...

Dynamic modal in Vue JS with custom components

Within the news.twig file {% extends 'layouts.twig' %} {% block content %} <section class="ls section_padding_bottom_110"> <div id="cart" class="container"> <cart v-bind:materials=" ...

Modifying Mongoose schema options does not update database entries

I defined a mongoose schema that looks like this: { Username: { type: String, unique: true, required: true, }, Password: { type: String, required: true, minlength: 10, maxlength: 20 } ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

How to create a CSS animation that gradually darkens a background image during a

Currently in the process of constructing a page with an intriguing background image: body { background:url(images/bg.png) center center no-repeat fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; ...

What steps do I need to take to create npm packages specifically for react-native development?

Which programming languages are essential for creating npm packages that work on both android and ios platforms in react-native development? Can you suggest any helpful documentation or blogs for developing npm packages that support ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

The process of incorporating a function into a website's source code using a web driver

In the source code, there is a button with an onclick event to change the paragraph content. However, the code provided does not seem to be functioning properly. ((JavascriptExecutor) this) .executeScript("function test123() { y=docume ...

A guide to filtering a JSON array by email address with JavaScript

How can I identify distinct elements in a JSON array using JavaScript? Below is the example of my JSON array. I need to determine the size of unique elements. [ { "_id": "5aaa4f8cd0ccf521304dc6bd", "email": "<a h ...

Angular promise did not assign a value to a variable

Can someone assist me with a problem I'm facing? After the first callback, the variable doesn't seem to change as expected. Below is my code snippet: this.handlerLocalDef = function(defer) { var hash = {}; defer.then( ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...