I've deployed my node.js app on heroku and now I'm trying to connect to this from my localhost:3000, but I've got this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blogs-backend-nodejs.herokuapp.com/api/user/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 503.
here below my Node app.js code:
import express from 'express';
import mongoose from 'mongoose';
import blogRouter from './routes/blog-routes';
import router from './routes/user-routes';
import cors from 'cors';
const port = process.env.PORT || 5000
const app = express();
const whitelist = ["http://localhost:3000"]
const corsOptions = {
origin: function (origin, callback) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error("Not allowed by CORS"))
}
},
credentials: true,
}
app.use(cors(corsOptions));
//Middlewares
app.use(express.json());
app.use("/api/user", router);
app.use("/api/blog", blogRouter);
mongoose.connect(
'mongodb+srv://Denys:130299dddd@cluster0.nqxcoxz.mongodb.net/?retryWrites=true&w=majority'
)
.then(() => app.listen(port))
.then(() =>
console.log('Connected')
)
.catch((err) => console.log(err));
As you see I have mongodb connected to my node.js app. I've allowed localhost:3000 origin, but still the same error from backend.
What is wrong? I'll be very appreciate for some help.
Thanks in advance!
You can try this.
import express from 'express';
import mongoose from 'mongoose';
import blogRouter from './routes/blog-routes';
import router from './routes/user-routes';
import cors from 'cors';
const port = process.env.PORT || 5000
const app = express();
let corsOrigins=[];
if(process.env.REQUEST_ORIGIN){
corsOrigins=[process.env.REQUEST_ORIGIN];
}
else{
corsOrigins=["http://localhost:3000"];
}
const corsOptions = {
origin: corsOrigins,
methods:['GET','POST'],
allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));
//Middlewares
app.use(express.json());
app.use("/api/user", router);
app.use("/api/blog", blogRouter);
mongoose.connect(
'mongodb+srv://Denys:130299dddd@cluster0.nqxcoxz.mongodb.net/?retryWrites=true&w=majority'
)
.then(() => app.listen(port))
.then(() =>
console.log('Connected')
)
.catch((err) => console.log(err));
I hope your error will solved.