I am trying to send JSON data to the server and receive. here is my server API code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
app.use('/api', router);
router.post('/', function (req, res)
{
res.json({ message: 'you are doing post ' });
})
app.listen(port);
console.log('Magic happens on port ' + port);
I have tested it with "postman" and it responded fine.
when I trying to get response from a client with the following code
function BestTourModel()
{
var self = this;
self.serverURI = 'http://localhost:8080/api';
self.ajax = function(uri, method, data)
{
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
success: function(data){alert(data);},
failure: function(errMsg) { alert(errMsg);}
};
return $.ajax(request);
}
self.run_algorithm = function()
{
if(self.input_value())
{
var markers = [{ "a": "11", "b": "7" },
{ "a": "44", "b": "19" },
{ "a": "45", "b": "-3" }];
self.ajax(self.serverURI(), 'POST', markers).done(function(data)
{
console.log(data); //this prints received data
});
}
}
}
var bestTourModel = new BestTourModel();
ko.applyBindings(bestTourModel, $('#main')[0]);
the "run_algorithm " is bound to an html button.
<button class="btn" data-bind="click: $root.run_algorithm" >Run</button>
I was tring to confirm the connection by sending the shown JSon data and hoping to receive something, so I can send my real data. but I got error in chrom debugger, shown below.
XMLHttpRequest cannot load http://localhost:8080/api. Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'null' is therefore not
allowed access.
Please point out what I am doing wrong. I am new to this, please explain in a simple way.
Thanks!