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
res.sendFile(htmlFilePath);
});
app.listen(3000, function () {
console.log('CORS-enabled web server listening on port 3000');
});
Project URL: