I can't set up CORS

I’m trying to learn Express CORS but I can’t seem to access my /protected API even when the request is coming from my allowed url. I’m probably making rookie mistake here’s my backend code.

const express = require('express');
const cors = require('cors');
const app = express();
const path = require('path');

// Create a custom middleware to check the origin for the products API
const productsCorsOptions = {
  origin: function (origin, callback) {
    if (origin === 'https://perfect-automatic-meal.glitch.me') {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));

// Use the custom CORS middleware only for the products API
app.use('/protected', cors(productsCorsOptions));

app.get('/protected', function (req, res, next) {
  res.json([{ msg: 'super secret data' }]);

app.get('/', (req, res) => {
  // Construct the absolute path to the HTML file based on the 'public' folder and the file name
  const htmlFilePath = path.join(__dirname, 'public', 'index.html');

  // Send the HTML file as a response

app.listen(3000, function () {
  console.log('CORS-enabled web server listening on port 3000');

Project URL:

The origin shouldn’t have a trailing slash from a look at the docs.


it doesn’t seem to make a difference in the error

the project is making a request from the same site, isn’t it? what value of origin is that middleware passing in that case?

i don’t know, it should just be allowing the same site to make the request

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.