学习 node.js 搭建web服务器

开始 学习使用 node.js 首先完成搭建一个 web服务器。myweb.js

 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
";
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

浏览器输入 127.0.0.1:3000

输入 127.0.0.1:3000/Double

原文地址:https://www.cnblogs.com/double405/p/7141353.html