Getting rid of the CORS error with NodeJS

Ideally what I am trying to solve here is an error that usually occurs when you are trying to server data to a different domain. You will usually get an error saying something similar to the below

Cross-Origin Request Blocked

So how do we now get rid of this assuming we are using a NodeJS server to serve the data. Easy we just add the cors module. SO here is the code

 

var express = require("express");
var cors = require("cors");
var app = express();

var jsonString = [
    {
        test_prop: "testVal1"
        
    },
    {
        test_prop: "testVal2"
    }
];

//// ============ Some code here ==============

//this is the solution. Use this line before the line the data gets served
app.use(cors());

app.get("/my-api", function(req, res) {
   res.json(jsonString);
});

app.listen(3000);

console.log("My app running on port 3000");

//// ============ Some code here ==============