Full error: “Access to XMLHttpRequest at ‘http://localhost:8080/api/tutorials’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”
On the frontend I am using NuxtJS. I am sending a simple post request at the node server hosted on localhost:3000, but it’s giving me this error even though I am using CORS in my app. The request is for inserting data in the mongodb database.
On the node server i.e. localhost:8080, I’ve tried:
var corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
Tried this too but no success:
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
Please tell if there is any solution for this error. Thank you.
EDITED:
Here, I am using axios to first create an instance (on the frontend). https://ibb.co/C2ChH5d
These are all the requests that I want to use. https://ibb.co/5TbSHjF
And this is the request that is being made currently(create). https://ibb.co/pPp8rdh
The nodeJS code: https://ibb.co/GFWMQW1
NodeJS code:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
require("./app/routes/tutorial.routes")(app);
var corsOptions = {
origin: "http://localhost:3000",
};
app.options("*", cors());
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to the database!");
})
.catch((err) => {
console.log("Cannot connect to the database!", err);
process.exit();
});
Advertisement
Answer
Well, the problem was that I was using the API routes before initializing cors()
. When I shifted the routes down the app.use(cors(corsOptions))
, the problem was solved.