The simplest way to verify that CORS is enabled is by simulating calls from different sources using curl or a similar tool. (We'll be seeing more of this in the following chapter, when we get to do some testing.) We can make it even simpler by writing up a small web page that will do a cross-domain GET, adding a dummy header to force CORS, and checking the network traffic. Our page is simplicity itself—totally no frills!
// Source file: src/cors_request.html
<html>
<head></head>
<body>
<script type="text/javascript">
const req = new XMLHttpRequest();
req.open('GET', 'http://www.corsserver.com:8080/', true);
req.onreadystatechange = () => {
if (req.readyState === 4) {
if (req.status >= 200 && req.status < 400) {
console.log(req.responseText)
} else {
console.warn("Problems!")
}
}
};
req.setRequestHeader("dummy", "value");
req.send();
</script>
</body>
</html>
We will be running our CORS server at www.corsserver.com:8080 (I'm actually hacking the /etc/hosts file on my own machine so that the server is actually in my machine itself), and we'll use the Web Server for Chrome to load and run our page. Check out the following screenshot for the results of doing this:
Using CORS is safer than other alternatives, including the old stalwart JSONP (JSON with Padding, a way to enable getting information across domains), so adding it to your server should be mandatory. However, as we've seen, it's simplicity itself with just a tad of Express middleware.