Sending and receiving data using javascript http

advertisements

I am sending data in json format from javascript using XMLHttpRequest and receiving data at node.js file as following

client.js

$.ajax({
    type: "POST",
    dataType: 'json',
    data: JSON.stringify(Idata),
    url: AjaxURL,
    success: function (result) {
        return true;
    }
});

server.js

var http = require('http');

console.log("server initialized");

var server = http.createServer(function (req, response) {
    req.on('data', function (data) {

        var d = JSON.parse(data);
        console.log("data : " + d.OperationType);

    });
    req.on('end', function () {
        response.end();
    });

}).listen(3000);

Now i successfully got the value of operationtype but the at client browser this error is showing:

XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.


The primary problem is that you are making a "GET" request. A data payload/HTTP request body cannot be uploaded with an XMLHttpRequest "GET" request. See the specification of XMLHttpRequest: "If stored method is GET act as if the data argument is null."

In order to send data, you should make a "POST" request, in this case:

xmlhttp.open("POST", AjaxURL, true);

In response to updated question:

For security reasons, your AJAX request will not be allowed to access your server hosted at localhost:3000 unless the AJAX request is initiated from a page served by localhost:3000 OR you tell your server to allow "cross-origin" requests. The latter can be accomplished by adding a line like this to your server:

response.setHeader("Access-Control-Allow-Origin", "*");

This sets a header that tells the browser to allow AJAX requests to localhost:3000 even if the request is initiated from a page that was not served by localhost:3000.