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:
- Install the
corspackage: First, you need to install thecorspackage in your project. In your terminal, navigate to the root directory of your Express application and run:
npm install cors
- Import the
corspackage: In yourindex.jsfile, import thecorspackage at the beginning of the file:
const express = require('express');
const cors = require('cors');
- Use the
corsmiddleware: Add thecorsmiddleware 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.
- 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.