HowTo: CORS-HTML-Express

When trying to use a web service from a HTML-page within a browser, one can be confronted with limitations on cross origin resource sharing when the web service has a different origin than the web page (different IP address or different port number). Browsers have a standard policy to prohibit accessing resources from other origins because of various security risks involved. To partially lift this restriction, and be able to access data sources on other origins, the CORS (Cross Origin Resource Sharing) protocol was developed. CORS works if the HTTP request contains certain headers, and the addressed server replies with certain headers. Insertion of the appropriate headers is a low-level activity that is supported now by most libraries and frameworks. In this example the request is made with the fetch method, that offers means to indicate that CORS headers have to be added. The web service is made with Express in this case, and also Express offers means to provide CORS headers in a declarative way.

Web service build with Express, containing a middleware function that inserts the required headers (file webservice.js):

var express = require('express');
var app = express();
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
app.get('/value', function(req, res) {
    res.send('1234567890');
});
app.listen(6060, function() {
    console.log('Webservice published on port 6060...');
});

Web page, containing a fetch operation with CORS headers. The easiest way to serve one static HTML page is to embed it in an Express web service accessible via one fixed path (file httpserver.js).

var express = require('express');
var app = express();
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
app.get('/page.html', function(req, res) {
    res.send(`
<!DOCTYPE html>
<html>
    <head>
        <title>Webservice & CORS</title>
    </head>
    <body>
        <h1>Value from webservice with different origin with CORS protocol:</h1>
        <p id='pid'></p>
        <script>
            fetch('http://localhost:6060/value', {
                method: 'GET',
                mode: 'cors',
            }).then(response => {
                return response.text();
            }).then(result => {
                document.getElementById('pid').innerHTML = result;
            });
        </script>
    </body>
</html>`);
});
app.listen(5050, function() {
    console.log('HTTP server listening on port 5050...');
});

To make things work, one has to set up a JavaScript project with the following package.json file:

{
  "name": "MinimalCorsHtmlExpress",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "keywords": [],
  "author": "J.C. Verheul",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.0"
  }
}

The project is build and executed with NPM and Node, so both tools should be installed on your workstation. For this example I used NPM version 5.5.1 and Node version 8.9.3. Older and newer versions of these tools should most likely work as well, since the project is extremely simple. Proceed as follows:

* Put the files webservice.js, httpserver.js and package.json in one working directory, or clone the little project from GitHub.
* Execute npm install
* Execute node webservice.js
* Execute node httpserver.js (from a different command prompt)
* Use a browser to visit http://localhost:5050/page.html