'Why do I have the CORS policy error in my browser? CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I have installed cors via npm and used the app.use(cors());middleware, but it is not solving my issue. I am running my frontend React App on Port localhost:3000
Access to XMLHttpRequest at 'http://localhost:3087/authenticate-token' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here below is the whole code from my app.js file:
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require("dotenv");
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
// const request = require('req')
const app = express();
dotenv.config();
// Parse Application/json
app.use(bodyParser.json());
// Base URL
// app.locals.baseURL = "h";
app.use(cors());
app.use(
session({
secret: process.env.ACCESS_TOKEN_SECRET,
saveUninitialized: true,
resave: false,
cookie: {
secure: true,
},
})
);
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB Connected"))
.catch((err) => console.log(err));
// Routes
app.use("/", require("./routes/auth"));
app.use("/pages", require("./routes/pages"));
app.use("/signUpModule", require("./routes/signUpModule"));
app.use("/users", require("./routes/users"));
const PORT = process.env.PORT || 3087;
app.listen(PORT, console.log(`Server running on ${PORT}`));
Below I have added the code from my end point:
const express = require("express");
// Authenticate Token
router.get(
"authenticate-token",
authFunctions.authenticateToken,
(req, res) => {
res.send({user: req.user, tokenValid: true});
);
Solution 1:[1]
So, it so happens that the issue was coming from the client-side where I was using axio to make a request. At first I had the following:
export const userAuthenticated = async (token) => {
const response = await axios.get(`${API_BASE_URL}/authenticate-token`, {
headers: {
authorization: token,
}
});
if (response.statusText === "OK") return response.data;
};
Then later, I changed to the following, which worked:
export const userAuthenticated = async (token) => {
const response = await axios({
headers: {
authorization: token,
},
method: "get",
url: `${API_BASE_URL}/authenticate-token`,
});
if (response.statusText === "OK") return response.data;
};
Solution 2:[2]
Try to add this to your app.js file:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
// "Access-Control-Allow-Origin",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method == "OPTIONS") {
res.header("Access-Control-Allow-Methods", "GET PATCH DELETE POST PUT");
return res.status(200).json({});
}
next();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Klem Lloyd Mwenya |
| Solution 2 | Theodor Peifer |
