Encountering a CORS blockage: The request header authorization is restricted by Access-Control-Allow-Headers in the preflight response

I encountered an error message that says:

Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

This occurs whenever I attempt to post data to my API using the axios command below:

  const [login, setLogin] = useState(
    localStorage.getItem('userInfo')
      ? JSON.parse(localStorage.getItem('userInfo'))
      : null
  );
const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${login.token}`,
      },
    };
 await axios
      .post(`${Config.SERVER_ADDRESS}/api/investments`, investmentObj, config)
      .then((response) => {
        console.log(investmentObj);
        notify(`${response.data.name} investimento cadastrado com Sucesso`);
        history.push(`/app/investment/${response.data._id}`);
      })
      .catch((err) => {
        console.log(err);

        notify(err.response.data, 'danger');
      });

I am confused about what steps to take as I have added the following middleware:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
  );

  app.use(cors());
  next();
});

I suspect that the issue lies with the Authorization in the headers, given that my other API calls are functioning correctly. I would greatly appreciate any assistance with resolving this preflight request dilemma.

Answer №1

After implementing the code snippet app.options('*', cors());, my project is finally up and running smoothly. For further details, refer to the CORS npm documentation available at https://www.npmjs.com/package/cors#enabling-cors-pre-flight

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
  );

  app.use(cors({ credentials: true, origin: true }));
  next();
});
app.options('*', 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

Clickable Href in jquery autocomplete

These are the codes I am currently using: <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.1 ...

Utilizing JavaScript within the Spring MVC form tag

Can you please assist me with the following question? I am currently working on a project using JSP, where we are utilizing Spring form tags. My issue involves creating two radio buttons that, when clicked, will display different options and pass the sele ...

"Despite not preferring to use the CORS wildcard, I am encountering a CORS wildcard error

I'm currently in the process of developing a web application using node, express, and Vue3 My goal is to submit a form to an endpoint located on my router at '/match/matchpost'. I have previously tested this endpoint successfully. However, ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Adjust the size of the embedded iframe to match the dimensions of the containing div

Is there a method to resize the iframe embed code for a vine so that it fits within the boundaries of the enclosing div? The supplied embed code already includes sizing information as shown below: <iframe src="https://vine.co/v/iMJzrThFhDL/embed/simp ...

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

Leverage the multiSubnetFailover feature within sequelize and mssql libraries

I am running a backend application using Node.JS that relies on the mssql (v7) and sequelize (v6) npm packages. Due to the fact that my production DB configuration can only be accessed by an AGL, I have to include multisubnetfailover=true in the DB connec ...

Utilizing NodeJS, Express, and the Jade template engine to insert JSON data into

While trying to follow a tutorial on NodeJS, Express, Jade, and MongoDB, I ran into a frustrating issue. Despite reading through various forum threads and attempting the suggested solutions, I still can't seem to make the POST command work. Please di ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

Troubleshooting the insertion of post query SQL using the express framework

Hey there! I'm currently working with MYSQL and express for my project. Whenever I attempt to query a POST request, I keep getting this error message: ER_BAD_FIELD_ERROR: Unknown column '$1' in 'field list' I understand that the ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

How can we extract word array in Python that works like CryptoJS.enc.Hex.parse(hash)?

Is there a method in Python to convert a hash into a word array similar to how it's done in JavaScript? In JavaScript using CryptoJS, you can achieve this by using: CryptoJS.enc.Hex.parse(hash), which will provide the word array. I've searched ...

What is the correct method for accessing an array within an object that is nested inside an array within a JSON file in Angular?

In my Angular controller code, everything is functioning properly except for the $scope.Product. I am unable to access the array of product details. Here is the relevant code snippet: .controller('aboutCtrl', function ($scope, aboutService) { ...

How can I determine if my clients are utilizing the CDN or NPM versions of my JavaScript library?

At this moment, I'm contemplating releasing an open-source version of my library on NPM. My main concern is figuring out how to track the usage of my CDN or NPM by clients. Is there a method available to achieve this? ...

Personalized Angular dropdown menu

Recently, I've started delving into angularJS and I'm eager to create dropdowns and tabs using both bootstrap and angular. Although there is a comprehensive angular bootstrap library available, I prefer not to use it in order to gain a deeper und ...

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

Select all elements using jQuery that have an id attribute and belong to a specific class

I am attempting to select all items with an ID attribute that starts with a specified string while also having a particular class. For instance, consider the following: <div id="test-id-1" class="test"></div> <div id="test-id-2" class="test ...

Data transfer from server to client using Node.js and express

Hello there! We have just begun diving into server-side code in school and it's definitely a challenge. I'm currently working on connecting my client-side JavaScript to my server-side JavaScript, where the server side contains an array of 2 objec ...