[React/MongoDB/Express] CORS Cross-Origin Request error from own Express Server

Hey Team, I’m building a CRUD with React/MongoDB and am experiencing a lot of trouble with CORS.

I handle the server via Express and the database is MongoDB. It’s one of those situation where it worked fine previously, but has since spit the dummy.

The frontend can’t access the data due to this error (gathered from firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5000/sessions/. (Reason: CORS request did not succeed). 

Interestingly, Chrome yields this error (it used to yield an error similar to above):

Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR 

From what I gather, I’m supposed to be adding a Cross Origin Header to the requests? or the server? But I can’t find anyway to do that. Other sources says cors(); covers all of it.

The corsEverywhere package gets requested a lot too, but it looks like it’s been taken down. I’ve tried cors disabling firefox extensions but it doesn’t have an effect.

End Goal is to resolve the CORS issue without breaking too many standard security guidelines. I need to have this running from a localhost and a Heroku Deployment.

It looks like the code isn’t even getting to the authentication stage (i.e. accessing mongodb), as when I deliberately make the password incorrect, it still yields the same error.

Here’s my server code:

//Basic Boilerplate for establishing server 

const express = require(‘express’); const cors = require(‘cors’); const mongoose = require(‘mongoose’);


const app = express(); const port = process.env.PORT || 5000; const uri = process.env.REACT_APP_ATLAS_URI;

//Middleware app.use(cors()); app.use(express.json());

//Connecting to DB mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true } ); const connection = mongoose.connection; connection.once(‘open’, () => { console.log(“MongoDB database connection established successfully”); })

//Initialising Routes const sessionRouter = require(‘./routes/session’); const campaignRouter = require(‘./routes/campaign’);

app.use(‘/sessions’, sessionRouter); app.use(‘/campaigns’, campaignRouter);

//Initialising Port 

app.listen(port, () => { console.log(Server is running on port: ${port}); });

I’m also including an example Routes file below:

const router = require('express').Router(); 

let Session = require(‘../models/session.model’);

router.route(‘/’).get((req, res) => { Session.find() .then(sessions => res.json(sessions)) .catch(err => res.status(400).json(‘Error: ‘ + err)); });

//CREATE SESSION router.route(‘/add’).post((req, res) => { const campaign = req.body.campaign; const character = req.body.character; const sesLog = req.body.sesLog; const date = Date.parse(req.body.date); //2009-06-15T13:45:30 for testing

const newSession = new Session({ campaign, character, sesLog, date, });

newSession.save() .then(() => res.json(‘Session added!’)) .catch(err => res.status(400).json(‘Error: ‘ + err)); });

//RETRIEVE SESSION router.route(‘/:id’).get((req, res) => { Session.findById(req.params.id) .then(exercise => res.json(exercise)) .catch(err => res.status(400).json(‘Error: ‘ + err)); });

//UPDATE SESSION router.route(‘/update/:id’).post((req, res) => { Session.findById(req.params.id) .then(session => { session.campaign = req.body.campaign; session.character = req.body.character; session.sesLog = req.body.sesLog; session.date = Date.parse(req.body.date);

session.save() .then(() => res.json(‘Session updated!’)) .catch(err => res.status(400).json(‘Error: ‘ + err)); }) .catch(err => res.status(400).json(‘Error: ‘ + err)); });

//DELETE SESSION router.route(‘/:id’).delete((req, res) => { Session.findByIdAndDelete(req.params.id) .then(() => res.json(‘Session deleted.’)) .catch(err => res.status(400).json(‘Error: ‘ + err)); });

module.exports = router;

Let me know if you’d like me to share more code, Thanks in advance!

submitted by /u/BeansInTheToilet
[link] [comments]