2014年7月13日 星期日

createServer建立監聽事件

使用腳本編輯器如Sublime Text建立一個js檔案
並且將Terminal或是commend(cmd)切換到工作目錄準備



http.js
var http = require('http');
http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.write('<h1>Node.js Hello World</h1>');
    res.end();
}).listen(80,'127.0.0.1',function(){
    console.log('Server is Run');
});
shell $>node http.js

開啟 http://127.0.0.1 或是 localhost


 createServer總共帶兩個事件,一個是request要求事件,一個是response回應事件,res.writeHead第一個提供的回應事件是200,是HTTP狀態碼,表示請求已成功,再來是Content-Type,指定為text/html ,res.write();中帶入任何的值,也可以使用html標籤, end()表示將這些事件送出,其中也可以帶入與write()一樣的任何值。
listen()是建立監聽,讓server監聽port, 第一個使用的是默認的port : 80, 通常指定8080 (網址為localhost:8080), 再來是指定監聽的ip, 127.0.0.1或是使用本機位址 192.168.x.x也可以!

沒有留言:

張貼留言

© Mac Taylor, 歡迎自由轉貼。
Background Email Pattern by Toby Elliott
Since 2014