Receiving CORS error when deployed with Docker in Katacoda Environment

397 Views Asked by At

I am working on a Katacoda scenario, deploying a MERN application via Docker and docker-compose. When I run my project locally, it works perfectly. When I load it into the katacoda platform and use their generated URL, I receive CORS errors. I have been banging my head against the wall for awhile now.

Here is my server file in ExpressJS

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const cors_proxy = require('cors-anywhere');

const db = require('./db')
const movieRouter = require('./routes/movie-router')

const app = express()
const apiPort = 5000

app.use(cors());
app.options('*', cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

db.on('error', console.error.bind(console, 'MongoDB connection error:'))

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); 
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use('/api', movieRouter);

app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`))

Here is my api file in my Client (React)

import axios from 'axios'

const api = axios.create({
    baseURL: 'http://localhost:5000/api',
})

export const insertMovie = payload => api.post(`/movie`, payload)
export const getAllMovies = () => api.get(`/movies`)
export const updateMovieById = (id, payload) => api.put(`/movie/${id}`, payload)
export const deleteMovieById = id => api.delete(`/movie/${id}`)
export const getMovieById = id => api.get(`/movie/${id}`)

const apis = {
  insertMovie,
  getAllMovies,
  updateMovieById,
  deleteMovieById,
  getMovieById,
}

export default apis

Finally, here is my Router file (ExpressRouter)

const express = require('express')

const MovieCtrl = require('../controllers/movie-ctrl')

const router = express.Router()

router.post('/movie', MovieCtrl.createMovie)
router.put('/movie/:id', MovieCtrl.updateMovie)
router.delete('/movie/:id', MovieCtrl.deleteMovie)
router.get('/movie/:id', MovieCtrl.getMovieById)
router.get('/movies', MovieCtrl.getMovies)

module.exports = router

Here is the exact error

Access to XMLHttpRequest at 'http://localhost:5000/api/movie' from origin 'https://2886795282-3000-cykoria03.environments.katacoda.com' 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.

The request seems to be coming from the dynamically created URL made by Katacoda. Any ideas on how I can fix this?

0

There are 0 best solutions below