利用nodejs搭建服務器,測試AJAX


     最近學習了AJAX一直沒有進行過測試,前今天了解了Noejs搭建本地服務器下就嘗試了一下。通過AJAX請求的方式獲取HTTP服務器返回數據的代碼

首先創建一個serve.js的文件。並寫入以下代碼.

 1 var http=require("http");
 2 
 3 var server=http.createServer(function(req,res){
 4 
 5     if(req.url!=="/favicon.ico"){
 6 
 7         res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"http://localhost:63342"});
 8 
 9         res.write("hello,我是從服務器端接收的")
10 
11     }
12 
13     res.end();
14 
15 });
16 
17 server.listen(8888,"localhost",function(){
18 
19     console.log("開始監聽...");
20 
21 });

打開cmd進入相應的目錄文件夾下,我的存在e盤的node-demo文件夾下,只需輸入e:回車,cd node-demo 回車,最后 node serve.js,然后提示開始監聽...,說明本地服務器已經搭建好了.

在webstorm(因為webstorm下已經配置好了服務器環境其默認端口為:63342)會比較簡單,新建一個testAJAX.html文件具體代碼如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>ajax demo</title>
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link href="" rel="stylesheet">
</head>
<body>
<input type="button" value="點擊一下" onclick="GetData()" />
<div id="test">
    this is a  ajax demo
</div>
</body>
<script>
    function GetData(){
        var xhr=new XMLHttpRequest();
        xhr.open("GET","http://localhost:8888",true);
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
            document.getElementById("test").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.send(null);
    }
</script>
</html>

測試一下:

                                                                                                                                                                                             

一個簡單的小測試就成功了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM