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);
};
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