2017-07-14 90 views
0

我寫了一個簡單的node.js服務器和和ajax請求分別發送和接收請求。儘管每一個變化作出了不working.this是我的node.js服務器代碼...xmlhttprequest狀態始終爲0,在響應中沒有響應文本

var express=require('express'); 
var server=express(); 
server.get('/sampleResponse',function(req,res){ 
    if(req.method=="POST"){ 
     console.log('reache`enter code here`d post'); 
     res.status(200).send('connection successful'); 
    }else if(req.method=="GET"){ 
     console.log('reached get'); 
     res.status(200).send('connection successful'); 
    } 

}); 
server.listen('8001','127.0.0.1'); 

//////下面是我的html頁面...上的本地主機上運行:8100

<html> 
    <head> 
     <link href="lib/ionic/css/ionic.css" rel="stylesheet"> 
     <link href="css/style.css" rel="stylesheet"> 
     <script> 
      function submitLoginDetails(){     
       var JSONLoginObj={rollNo:document.getElementById("rollNo").value, 
           password:document.getElementById("password").value}; 
       /////////////////////////////////////////////////////////////// 
       var xhttp = new XMLHttpRequest(); 
       xhttp.onreadystatechange = function(){ 
        var xhrdata = ""; 
        if(xhttp.readyState == 4){ 
         if(xhttp.status == 200) 
          alert(xhttp.responseText); 
         else 
          alert(xhttp.status); 
         } 
       }; 
       xhttp.open("GET", "http://localhost:8001/sampleResponse", false); 
       xhttp.send(); 
      } 
     </script> 
    </head> 
    <body> 
     <ion-pane> 
      <ion-header-bar class="bar-stable"> 
       <h1 class="title">Login Page</h1> 
      </ion-header-bar> 
      <ion-content> 
       <form> 
        Roll Number:<br><br> 
        <input type="text" id="rollNo"><br><br> 
        Password:<br><br> 
        <input type="text" id="password"><br><br> 
        <button id="loginButton" onclick="submitLoginDetails();">Login</button> 
       </form> 
       <p id="demo"></p> 
      </ion-content> 
     </ion-pane> 
    </body> 
</html> 

when access the same page by clicking on link i get response but no response in xhttp.responseText. 

回答

0

這是一個跨域問題(CORS),這意味着您正試圖從當前域外發出請求(對於資源)。您需要允許設置Access-Control-Allow-Origin接受您的所有請求。

您可以通過添加以下行到你的的.js文件(其中,你有你的express.js代碼)

response.writeHead(200, { 
    'Content-Type': 'text/plain', 
    'Access-Control-Allow-Origin' : '*' 
}); 
+0

非常感謝大衛這樣做......你不知道如何對我來說很有價值。我花了好幾個小時才使它工作。 –

+0

可以請你給的鏈接到node.js和web開發的好教程(無html教程)......在此先感謝 –

+0

@VineetJain結帳在這裏列出的資源=> https://github.com/ vioan /的NodeJS學習資源 –