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

Create a PHP form that includes a dropdown menu for selecting the quantity, allowing users to insert multiple rows of data inputted into the form

My first time posting something here. The issue I'm facing is: I have an HTML form with various variables. A dropdown for Quantity that should insert the data into a MySQL table multiple times based on the chosen quantity. For example, if the dropd ...

ESLint does not recognize the components used in Element UI

I've been working with Vue.js and Element UI components. However, when I try to use elements like Input or Col, ESLint throws an error with the message invalid-end-tag. I have already added eslint-plugin-vue to my setup, so why isn't ESLint reco ...

Local working fine but encountering issues on Openshift, specifically with syncing npm package versions across environments (local and global)

As I develop a forum using Angular that connects with Node/Mongo, there are numerous requests required to populate the page with necessary data. While everything functions flawlessly locally, once uploaded to Openshift, the site displays various bugs and f ...

What could be the reason for the mismatch in size between the downloaded file in Express.js and the file size on the server?

My code using express.js is quite simple: app.get("/download", download); and export let download = async (req: Request, res: Response) => { const file = "/tmp/my-file.zip"; res.download(file); } The client-side code is also straightforward: im ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

Adjust the position of an image to move it closer to the top using CSS

I have a fiddle where I am trying to adjust the position of an image (keyboard) to match a specific design. https://i.sstatic.net/flqCH.png In my fiddle, the keyboard image is slightly lower than the desired position shown in the design. I am looking for ...

Jquery animate - callback is triggered before animation finishes running

Is there a way for the element to first expand in height and then apply a background image once the height change is complete? Currently, I am experiencing laggy performance as the background image is applied before the height animation finishes. Can som ...

Zoom feature available on various images

My current setup includes one main image and multiple thumbnails that can be clicked to change the main image. The issue I encountered was when using jqzoom on the main image, the zoomed image would go blank after changing. After researching on stack overf ...

Is it necessary to have separate SSL certificates for hosting a Vue app and an Express API on the same host using Nginx? How should Nginx be configured

My Ubuntu VPS hosts a dockerized Vue App served by Nginx with SSL set up. Additionally, I have a Nodejs Express container running on the same host and routing queries to a MySql database, listening on port 8080. Both components work independently - I can ...

What is the best way to retrieve the initial element from a map containing certain data?

I am attempting to retrieve the first image path directory from an API that contains an Image so I can assign the value to the Image source and display the initial image. However, when using fl[0], all values are returned. Below is the code snippet: {useL ...

Change the Bootstrap components according to the size of the screen

Is there a built-in Bootstrap feature to change an element's class based on screen size? I'm working on a webpage with scrollable card elements. On desktop, the cards are arranged horizontally, but on mobile they are stacked vertically, requirin ...

What are the steps to correctly implement async await in a standard sequence?

When I press the button onPress={() => Login()} First, I need to obtain a token by using the signInWithKakao function. Secondly, right after acquiring the token, if it is available, I want to dispatch the profile using the kakaoprofile function. Howev ...

Unable to initiate nodejs: openssl configuration encountered an error

Encountered this error while starting my Express node server: openssl config failed: error:02001003:system library:fopen:No such process The node still started successfully. I have no intention to utilize SSL. Below is the starting code snippet: .. ...

Refresh the context whenever the state object changes

Within my application, I am utilizing a PageContext to maintain the state of various User objects stored as an array. Each User object includes a ScheduledPost object that undergoes changes when a user adds a new post. My challenge lies in figuring out how ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

Is the return value null when trying to access a property in this.props?

While working with my actions, reducers, and store in the Redux setup for my Shop component, I encountered an issue. Even after passing mapStateToPros to the Shop component, attempting to access this.props.auth to fetch the current user's information ...

Easily linking a React app to MongoDB

I recently developed a basic react app using 'create-react-app'. The app includes a form, validation, and Bootstrap components. It may not be extravagant, but it functions flawlessly. Furthermore, I registered with MongoDB to obtain a compliment ...

Simple CSS for creating a "red alert badge" with a number count

Looking for the best way to display the popular red notification indicator with count in a consistent manner across various browsers. It seems tricky to achieve a design that looks seamless on all platforms, as different browsers interpret paddings differe ...

Guide to implementing error handling in a RESTful API using Express middleware routing

Imagine a scenario where we have a REST API with the following route: app.put("/users/:userId", verifyUser, isOwner, updateUser); In this setting, there are multiple ways things can go wrong. The user may lack authorization due to not being logged in or ...