Shoulder.dev Logo Shoulder.dev

Implementing CORS in benhall/express-demo

Scenario:

You are building a web application using benhall/express-demo, and you need to allow cross-origin requests from a specific domain. In this example, we will allow requests from "example.com".

Solution:

To enable Cross-Origin Resource Sharing (CORS) in your Express application built with benhall/express-demo, you can use the cors middleware. Here's a step-by-step guide on how to implement CORS:

  1. Install the cors package: First, you need to install the cors package in your project. In your terminal, navigate to the root directory of your Express application and run:
npm install cors
  1. Import the cors package: In your index.js file, import the cors package at the beginning of the file:
const express = require('express');
const cors = require('cors');
  1. Use the cors middleware: Add the cors middleware to your Express application:
const app = express();
app.use(cors({ origin: 'http://example.com' }));

In the example above, we've allowed requests only from "example.com". You can modify the origin value to allow requests from other domains or use a regex pattern.

  1. Testing: To test the CORS implementation, you can use a tool like Postman or make requests from a browser. Make sure the requests are being made from the allowed origin.

Tests:

To verify the CORS implementation, you can write tests using a testing framework like Mocha or Jest. Here's an example using Mocha:

const request = require('supertest');
const app = require('../index');

describe('CORS', () => {
  it('should allow requests from the allowed origin', async () => {
    const response = await request('http://example.com')
      .get('/')
      .expect('Access-Control-Allow-Origin', 'http://example.com');

    expect(response.status).toBe(200);
  });

  it('should deny requests from an unallowed origin', async () => {
    const response = await request('http://anotherdomain.com')
      .get('/')
      .expect('Access-Control-Allow-Origin', 'http://example.com')
      .expect(403);

    expect(response.body.message).toContain('Forbidden');
  });
});

In the example above, we've written two tests: one for requests from the allowed origin and one for requests from an unallowed origin. The tests use supertest to make requests and check the response headers and status.