Cross-origin resource sharing (CORS)

In this post, I’ll explain how to add HTTP headers to our requests. To send http requests to another domain, you have to add some headers to your requests. If you don’t have them, you probably will have this error message (click F12 on client for details).

XMLHttpRequest cannot load http://localhost:3000/subjects. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.


Adding these lines to your HTTP Server configuration (ExpressJS for myLibrary project) you’ll be able to stablish communication between servers located in different domain. In this example we define permission to allow access to our Client that uses the port 9000, because the Server uses the port 3000.

    // CORS configuration
    // Allow-Origin
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000');
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST, OPTIONS, HEAD');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, X-Powered-By');
    // Allow-Origin

Related Links