Sling Academy
Home/Node.js/Fixing Node.js & Express Error for Cross Origin Requests

Fixing Node.js & Express Error for Cross Origin Requests

Last updated: December 28, 2023

Understanding Cross-Origin Resource Sharing (CORS)

When you encounter a Cross-Origin Resource Sharing (CORS) error in Node.js with Express, it’s typically due to the same-origin policy enforced by web browsers for security reasons. This policy prevents a web page from making requests to a different domain than the one that served the web page. CORS errors often occur when your Node.js application’s backend (API) and frontend are hosted on different domains or ports.

Enabling CORS in Express

To fix CORS errors in an Express application, you need to set the appropriate headers that allow cross-origin requests. You can do this by setting the headers manually or by using the cors middleware.

Manual Header Setting

You can manually set CORS headers in your Express routes. Here’s an example:

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

// Middleware to enable CORS
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 
               'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

// Root route
app.get('/', (req, res) => {
    res.json({ message: 'CORS is enabled' });
});

// Define the server port
const PORT = process.env.PORT || 3000;

// Start the server
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Using cors Middleware

For a more straightforward approach, use the cors package. First, install the middleware:

npm install cors

Then, include it in your application:

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

const app = express();

// Enable CORS for all routes
app.use(cors());

// Root route
app.get('/', (req, res) => {
    res.json({ message: 'CORS is enabled' });
});

// Define the server port
const PORT = process.env.PORT || 3000;

// Start the server
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

This will enable CORS for all routes. If you need more granular control, for example, enabling CORS for specific routes or setting specific headers, you can configure the cors middleware accordingly.

Next Article: Node.js & Express Issue: req.body Empty – How to Fix

Previous Article: Fixing Node.js & Express Error: Request Entity Too Large

Series: Dealing with Common Errors in Node.js

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates