Nodejs學習筆記(一)如何創建服務端

    之前一直用的Java,現在開始學習Nodejs,作爲學習成果進行記錄總結。

在Node環境安裝好後,首先學習如何寫一個服務器程序,代碼如下(NodeStudy_1.js):

var  http  =  require('http');
http.createServer(function  (request,  response)  {
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    console.log('訪問');
    response.write('hello,world');
    response.end('  end');//不寫則沒有http協議尾,但寫了會產生兩次訪問
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');
在文件所在目錄運行:

D:\zhanglei\Study>node NodeStudy_1.js
Server  running  at  http://127.0.0.1:8000/

在瀏覽器中輸入:http://localhost:8000/

會出現如下:

hello,world  end

注意程序中有註釋的一行

response.end('  end');
如果不加該行,瀏覽器會一直轉圈、加載;加了會產生兩次訪問(有的瀏覽器只有一次,如火狐),如下:

D:\zhanglei\Study>node NodeStudy_1.js
Server  running  at  http://127.0.0.1:8000/
訪問
訪問

第一次訪問獲取的是hello,world,第二次是由於瀏覽器獲取favicon.ico導致,所以正確的寫法如下:

var  http  =  require('http');
http.createServer(function  (request,  response)  {
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url!=="/favicon.ico"){  //清除第2此訪問  
        console.log('訪問');
        response.write('hello,world');
        response.end('hell,世界');//不寫則沒有http協議尾,但寫了會產生兩次訪問  
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/'); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章