简体   繁体   中英

Why I'm getting empty result?

I'm learning JavaScript & Ajax & NodeJs.

I'm trying to build a web page which display a string from server.

The server code:

var express = require('express');
var app = express();

app.get('/sms', function (req, res) {
   console.log("Got request: " + req);
   res.send('Hello World');
   console.log("Send result");
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Listening at http://%s:%s", host, port)

})

The client code:

<html>
<head>
    <title> Test AJAX </title>
</head>
<body>      

     <p>    
        <button onclick="sendRequestForSms()"> Get SMS From Server </button>
        </br>
        <h1 id="smsId"> SMS: <h1>
     </p>

    <script type="text/javascript">

            var xmlhttp;
            if (window.XMLHttpRequest) 
            {
                xmlhttp = new XMLHttpRequest();
            }
            else 
            {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange = function() 
            {       
                  console.log('State: ' + xmlhttp.readyState + ' status: ' + xmlhttp.status);           
                  // 1: server connection established
                  // 4: request finished and response is ready
                  // 200: "OK"
                  // 404: Page not found
                  if (xmlhttp.readyState == 4)// && xmlhttp.status == 200) 
                  {
                        console.log('Got Result: ' + xmlhttp.responseText);
                        document.getElementById("smsId").innerHTML = xmlhttp.responseText;//"done";
                  }
            };

            function sendRequestForSms() {
                xmlhttp.open("GET", "http://127.0.0.1:8081/sms", true);
                xmlhttp.send();     
            }                                       
        </script>

</body>

</html>

After I'm clicking on the button I'm getting an empty string.

Here the log: State: 1 status: 0 Ajax1.html:1 XMLHttpRequest cannot load http://127.0.0.1:8081/sms . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. Ajax1.html:28 State: 4 status: 0 Ajax1.html:35 Got Result:

Why I'm getting an empty string ? what am I missing ? Thanks

Your client code and server code must be on the same origin (same hostname, same port) for you to make AJAX requests.

127.0.0.1 cannot send AJAX requests to 127.0.0.1:8081.

To fix, either reverse proxy your node.js to the same hostname (recommended), or set an Access-Control-Allow-Origin in node.js.

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