1

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!

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197

1 Answers1

2

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.

Chetan Ukani
  • 116
  • 4
  • Thanks I've took some piece of your code, and now it works fine! But I have just one question. What is REQUEST_ORIGIN? Is it some const var in heroku .env? Or I need to create .env and add there REQUEST_ORIGIN and something more?:) – user17880509 Jul 28 '22 at 16:24
  • 1
    I have hard coded of corsOrigins because this is now in development. But when our project is going in production then we have to set REQUEST_ORIGIN in our .env file. so I hope now you are getting my point. – Chetan Ukani Jul 29 '22 at 04:25