John Yacoub
John Yacoub

Reputation: 91

Nodejs Cors issue Nodejs and React (production)

I have an issue getting requests from the browser and it is getting annoying! Any hints are highly appreciated. Thanks in advance!

I have nodejs setup as follows:

const express = require("express");
const cors = require("cors");
const app = express();

app.use(
  cors({
    origin: "*",
    methods: "GET,POST",
    allowedHeaders: "Content-Type,Authorization",
    credentials: true,
    preflightContinue: true,
  })
);
app.use(express.json());
....

in Reacr Axios requests as follow

const getComments = () => {
  const config = {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
    },
    method: "GET",
    url: `${url}/all`,
    withCredentials: true,
    crossorigin: true,
    "Access-Control-Allow-Origin": "*",
  };
  return axios(config)
    .then(serviceHelper.onGlobalSuccess)
    .catch(serviceHelper.onGlobalError);
};

Cors Error I am getting

Upvotes: 0

Views: 2034

Answers (2)

This line

allowedHeaders: "Content-Type, Authorization"

tells the server to allow only these headers. If you look into your request, you have this header.

"Access-Control-Allow-Origin": "*"

This will be included in the header while making a request. This is getting rejected by the server.

Instead of that, try this

const getComments = () => {
  const config = {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",

    },
    method: "GET",
    url: `${url}/all`,
    withCredentials: true,
  };
  return axios(config)
    .then(serviceHelper.onGlobalSuccess)
    .catch(serviceHelper.onGlobalError);
};

regards, Jay

Upvotes: 0

Bhagyashri Machale
Bhagyashri Machale

Reputation: 219

You can try this in your nodejs code

const express = require('express');
let server = express();
server.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With,Content-Type,Accept'
  );
  next();
});

Upvotes: 1

Related Questions