nodejs学习【第一节】创建web服务器

创建server.js

var http = require('http');
var fs = require('fs');
var url = require('url');

// 创建服务器
http.createServer( function (request, response) {  
   // 解析请求,包括文件名
   var pathname = url.parse(request.url).pathname;
   // 从文件系统中读取请求的文件内容
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{             
         response.writeHead(200, {'Content-Type': 'text/html'});    
         // 响应文件内容
         response.write(data.toString());        
      }
      //  发送响应数据
      response.end();
   });   
}).listen(3000);

在该目录下创建一个 index.html 文件
运行node server.js
在浏览器访问localhost:3000/index.html

猜你喜欢

转载自blog.csdn.net/weixin_45561719/article/details/100046737
今日推荐