Skip to main content

Command Palette

Search for a command to run...

[WIL] What is CORS?

05/07/23

Published
[WIL] What is CORS?

This week's reflection

  • Planning for the main project in my specialization, collaborating on both the front-end and back-end

  • API design and Jest unit testing

What is CORS?

  • CORS stands for Cross-Origin Resource Sharing, which refers to the sharing of resources across different origins.

  • By default, if a client sends a request to a server with a different domain, the request will be blocked. For example, if a client at localhost:8000 sends a request to a server at localhost:8080, the server will block the request because it came from a different port, i.e., a different domain. This will result in an error that says "Access-Control-Allow-Origin" header is missing.

  • To solve the CORS issue, we need to add the "Access-Control-Allow-Origin" header to the response header. This header indicates that we allow the request from the client domain.

// Allow all CORS 
Access-Control-Allow-Origin: *

// Allow specific domain 
Access-Control-Allow-Origin: http

CORS library in Node Express

In Node.js with Express, we can use the CORS library:

  1. First, install the cors library

    const cors = require('cors');

  2. To allow access from all domains

    app.use(cors());

  3. To allow access only from specific domains:

     const cors = require('cors');
    
     let corsOptions = { origin: 'https://www.domain.com', credentials: true } app.use(cors(corsOptions));