使用Node.js + HTTP搭建Web服务器

使用Nodejs + http 搭建web服务器

  • 首先创建一个server.js文件,创建服务器,以及对应css和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;
      //输出请求的文件名
      console.log("Request for "+ pathname + "  received.");
    //获取后缀,判断是js还是css文件,如果目录结构不同,此处需要修改
      var firstDir = pathname && pathname.split('/')[1];
      var ContentType = {'Content-Type': 'text/html'};
      // js - application/x-javascript
      if (firstDir && firstDir === 'static') {
        ContentType = {'Content-Type': 'text/css'};
      }
      if (firstDir && firstDir === 'js') {
        ContentType = {'Content-Type': 'application/x-javascript'}
      }
      //从文件系统中去请求的文件内容
      fs.readFile(pathname.substr(1),function(err, data) {
        if(err) {
          console.log(err);
          //HTTP 状态码 404 : NOT FOUND
          //Content Type:text/plain
          response.writeHead(404, {'Content-Type': 'text/html'});
        }
        else {
          //HTTP 状态码 200 : OK
          //Content Type:text/plain
          response.writeHead(200, ContentType);
          //写会回相应内容
          response.write(data.toString());
        }
        //发送响应数据
        response.end();
      });
    }).listen(8080);
    console.log('Server running at http://127.0.0.1:8080/');
  • 创建一个简单的html页面 ,此处是两个边框,然后是一个表格,并在第二个边框添加上一个点击事件,作为引入另一个js文件

  • css样式文件和上面写的style标签内容一样

body {
border: 1px solid blue;
}
div {
    border-radius: 10px;
    width: 400px;
    height: 200px;
    border: 2px solid yellow;
}
  • 这个是js文件
    console.log(’-成功引入js文件-’);
    function onClickDiv () {
    alert(‘second点击事件’);
    }

整体上就这么多了!详细的都有注释,大家可以自己看看,相对上也比较简单,具体步骤我也简单说下:

1、下载安装nodejs,官网就可以了,此处使用的是http,也有的例子使用的是express(需要在nodejs中下载,详细的自己可以百度下看看)
2、进入到此项目中js文件那层目录,执行node server.js(此处取名为server,具体看自己的名称)
3、执行成功会打印服务器启动,并显示ip和端口号
4、打开浏览器http://127.0.0.1:8080/index.html即可查看效果

最后上图:
图片[1]-使用Node.js + HTTP搭建Web服务器

图片[2]-使用Node.js + HTTP搭建Web服务器

- - - - - 本页内容已结束,喜欢请分享 - - - - -

感谢您的来访,获取更多精彩文章请收藏本站。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容