简体   繁体   中英

How to make a jQuery request to a locally hosted node.js server?

I have a simple node.js server saved in a file called server.js, the code for which is below:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8010);

I am running this locally in command line (with node.js installed) by executing

node server.js

If I then access this in my browser (google chrome) with the URL my.local.IP.address:8010 it displays hello world successfully.

I am also creating a webpage that will execute this jQuery as soon as the page is loaded:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>    
    $(document).ready(function(){
        $.get("http://my.local.IP.address:8010/", function(){
            alert("Success");
        }).fail(function(err){
            alert("Failed");
            alert(JSON.stringify(err));
        });
    });
</script>

When I open this html file in my browser it always creates an alert box saying failed followed by this stringified JSON object as the error (I've formatted it so it is easier to read):

{
"readyState": 0,
"status" : 0,
"statusText": "error"
}

This happens no matter how many times I've tried while the node.js server is running locally. I have also tried to make an async XMLHTTP request function that does it myself, and this does not work either.

I know both the jQuery and the XMLHTTP function I made work correctly since if I call the functions on the URL https://httpbin.org/get it will return successfully.

Any ideas as to where I have gone wrong?

It's a cross domain issue. Browser thinks your page is not part of http://localhost:8081 server. You need to change server code as follows in order to make it work.

http.createServer(function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8010);

I guess it may be a cross domain issue, as you are using your IP address in the call, and localhost:8010 on the browser url to access your site. It is a problem common to ajax requests, and has nothing to do with Node.js

Try using the same url to access the site than the one you are targeting to.

See this similar issue with cross domain

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM