The CORS policy has blocked the 'Access-Control-Allow-Origin' header

My expertise lies in creating API, BackEnd, and Frontend websites.

For the API, I utilize Express, while for the BackEnd - FrontEnd, I rely on ReactJs.

During local testing, everything functions as expected. However, upon deployment to the server, error messages are generated:

Access to XMLHttpRequest at 'http://domain/headline' from origin 'http://domain' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

and

Access to XMLHttpRequest at 'http://domain/marketData/snack' from origin 'http://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Within my ReactJs setup, I make use of axios for data retrieval.

Moreover, in my nginx server configuration, I have included the following settings:

location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:3001;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
        if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' 'http://domain';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
            }
    }

I am puzzled as to whether I might have overlooked something critical.

Answer №1

To implement CORS in your API server, begin by installing the cors package from npm. You can do this by running npm i cors. Once you have installed the package, add the following lines of code to your main file such as app.js, server.js, or index.js which is responsible for creating the HTTP service:

const cors = require('cors');
app.use(cors());
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

Navigating out of a Modal in React: A step-by-step guide

I have a button on the initial page of my web application. When this button is clicked, a modal form pops up. Upon submitting this form, an API call is made to update the database with no response expected as it's a one-time entry. As this is the sta ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

Using React-Router-Native to send an image as a parameter

I am encountering an issue while attempting to pass an image as a parameter in react-router-native and retrieve the data from location.state. Typically, I use the following code to display an image: import Icon from '../image/icon.png'; <Vie ...

Simulated FTP Connection Setup and Error Event in Node.js using Typescript

In my Node-Typescript-Express application, I am utilizing the FTP library to connect and retrieve files from a designated location. As part of creating unit tests, I am focusing on mocking the library to ensure coverage for code handling Ready and Error ev ...

Upon being provided with a route param, the response will be

For my current project using Express, I want to implement Reddit-like functionality where appending ".json" to any URL will return JSON data instead of the rendered template. To set up the rendering engine in Express, I am using Jade. Here is how I config ...

The `href` property did not match in Next.js server

I encountered this error while working on my Next.js project and refreshing the page. https://i.stack.imgur.com/aCipA.png The issue lies within the NavBar component, here is the code snippet: import Link from "next/link" import { useRouter} from ...

Error: Missing authorization header on certain requests for Axios in iOS devices

I have a vuejs application where I am utilizing axios for handling HTTP requests. The authorization header is being set through a request interceptor, like this: const api = axios.create({ baseURL: process.env.API_URL, crossdomain: true, headers: { ...

The pre-save function in Mongoose Schema fails to execute the next() function upon calling

In the process of developing a straightforward application that involves user sign up and login features, I have created the following user schema: // User Schema const userSchema = new mongoose.Schema({ username: { type: String, requ ...

Leverage React Final Form to dynamically adjust conditions based on the values within the form

To dynamically generate a specific number of fields based on user input from the initial form step, I am utilizing a multi-step form with a "Wizard" class as the <Condition /> component does not fit my requirements. Essentially, I need to retrieve v ...

Experimenting with Jest for pagination of tables in a React Material-UI component

Recently, I implemented a basic MUI data table with pagination from the following link: https://mui.com/material-ui/react-table/. The issue arose when trying to test it on the NEXT page using Jest. Whenever I attempted to change the row numbers from 5 to 1 ...

Steps to convert HTML <li> elements into HTML <datalist> elements

In my HTML file, I have a list of objects within li elements that I would like to transfer to an HTML datalist within the same file. I am currently working on a Node.js Express framework application where the data within the li elements is coming from an S ...

Exploring the ‘ref’ feature in React alongside Material-UI

In my attempt to access input data through React's "ref" attribute on a TextField in Material-UI, I've encountered some difficulties. It doesn't seem straightforward to achieve this using the 'inputRef' or 'inputProps' me ...

Utilize inherited autocomplete/suggestion prop types within the wrapping component

I am currently developing my own customized "wrapper" for a Chakra UI component. This wrapper allows me to include additional props, methods, and any other functionalities that I may require in the future. However, one drawback of this approach is that I ...

Is there a way to make sure that the antd datepicker response is sent to the backend only after I click on the submit button?

After receiving a response from the antd datepicker and successfully sending it to the backend, I encountered an issue. The response is automatically sent to the backend as soon as a date is selected. However, I want the request to be sent only after click ...

Encountering a 404 error when using Vue history mode in conjunction with an Express

I'm facing an issue with my Vue SPA hosted on an Express server. Whenever I use history mode and refresh the page, I encounter a 404 not found exception. I attempted to solve this problem by utilizing the connect-history-api-fallback package but unfor ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

If the status is 400, Xhr does not log the response

I have implemented a basic login route in express: //login router.post('/login',async (req,res) => { try{ const user = await User.findOne({username: req.body.username}); console.log(user); if (!user) { ...

executing Windows Command Prompt commands through package.json scripts

When running commands in the command line (cmd), I have a specific sequence that I need to follow. The first command is 'npm run build' After that, I need to execute: 'xcopy C:\fileOne C:\fileTwo' However, I would like ...

What is the best way to adjust the size of a button using CSS within a ReactJS

I am facing an issue where I need to create a button with a specific width, but the template I'm using already has predefined styles for buttons. When I try to customize the button's style, nothing seems to change. Below is the code snippet: Her ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...