2

Maybe this seems a really noob question, but I can't figure out what I do wrong. What I want to accomplish is a simple AJAX request. Here is my code on server side:

http.createServer(function(request, response) {
        response.writeHead(200, {
            "Content-Type": "text/html"     
        });
        response.end("No data to return.");

}).listen(8666);

On client side I use jQuery:

$(document).ready(function() {
        $("#magicSend").on("click", function() {
            $.ajax({                   
               url: "http://localhost:8666/",
               type: "POST"
             });
        });
    });

The problem is, that according to Firebug I'm getting the response headers but not the content. The AJAX call also gets red on Firebug's console, although it shows "200 OK". I know I miss something but can't figure out what.

Faluvegi Ferenc
  • 343
  • 2
  • 10

2 Answers2

2

Are you running your webserver on port 8666 also? Judging by your code, all your NodeJS server does is serve a single answer, so I'm guessing not. You cannot make AJAX calls to a different port, even if it's the same host (localhost in your case).

Peeter
  • 9,282
  • 5
  • 36
  • 53
  • I'm running a simple LAMPP server, which runs on port 80. I used as example the code from the first answer of this question: http://stackoverflow.com/questions/6011984/basic-ajax-send-receive-with-node-js – Faluvegi Ferenc Aug 19 '12 at 13:07
  • I found a workaround by using JSONP, as described here: http://remysharp.com/2007/10/08/what-is-jsonp/ – Faluvegi Ferenc Aug 19 '12 at 13:47
  • Like I said, you cannot use AJAX calls on seperate hostnames/ports. JSONP is a valid work-around. – Peeter Aug 19 '12 at 14:22
0

Is not working because of the same origin policy.

It maybe not obvious but browsers also enforce the policy down-to the port number.

So http://example.com:80 is different from http://example.com:81

You can get around it with jsonp.

jamjam
  • 3,171
  • 7
  • 34
  • 39