0

我正在研究 Katacoda 场景,通过 Docker 和 docker-compose 部署 MERN 应用程序。当我在本地运行我的项目时,它运行良好。当我将它加载到 katacoda 平台并使用它们生成的 URL 时,我收到了 CORS 错误。我已经把头撞在墙上有一段时间了。

这是我在 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}`))

这是我api在客户端(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

最后,这是我的路由器文件(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

这是确切的错误

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.

该请求似乎来自 Katacoda 动态创建的 URL。关于如何解决这个问题的任何想法?

4

0 回答 0