學習 node.js 搭建web服務器

開始 學習使用 node.js 首先完成搭建一個 web服務器。myweb.jsnode

 1 var http = require('http');
 2 var url = require('url');
 3 var hostname = '127.0.0.1';
 4 var port = 3000;
 5 var bodystr = "";
 6 var server = http.createServer(function(req, res){
 7   res.statusCode = 200;
 8   res.setHeader('Content-Type', 'text/plain');
 9   var pathname = url.parse(req.url).pathname;
10   if(pathname === "/"){
11         bodystr = "Hello World\n";
12   }else{
13         bodystr = req.url;
14   }
15   res.end(bodystr);
16 }).listen(port, hostname, function(){
17   console.log(`Server running at http://${hostname}:${port}/`);
18 });

使用 npm 執行 myweb.js
web

瀏覽器輸入 127.0.0.1:3000npm

輸入 127.0.0.1:3000/Double瀏覽器

相關文章
相關標籤/搜索