After trying various solutions, I finally figured out the one that works like a charm!
Run the following command from the project root directory:
npm install request
//Enabling CORS on ExpressJS
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();
});
//Making an API call from NodeJS server
// Posting field (json object) to mocky.io
var request=require('request');
var mockyPostRequest = {
url: 'http://www.mocky.io/v2/596a5f03110000920701cd92',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: field
};
request(mockyPostRequest, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
// Logging the post data on the console
console.log(body);
}
});
I used following as the reference:
https://enable-cors.org/server_expressjs.html
Thanks everyone for replying.