Node(v6.5.0)--HTTP-NO.1(单页面的部署)

单页面的部署

摘要:1、我也不知道是不是叫单页面部署,就是把你做的html页面,监听起来,然后在浏览器上面输入地址就能访问了;
2、其实跟我们昨天写的一样,就是把html文件读取出来,然后在写到浏览器页面上response.end(data)/response.write(data);response.end()

  1. 访问index.html
    1. 在浏览器中输入“127.0.0.1:8000”就能得到index.html的页面了;
    2. 这里写图片描述
目录结构:
-----public---index.html 
-----http.js

//======================
const http = require("http");
const fs = require("fs");
http.createServer(function(req,res){
    fs.readFile("public/index.html", function(err,data){
        res.writeHead(200,{"Content-Type":"text/html"});
        res.write(data);
        res.end();
    })
}).listen(8000,"127.0.0.1")

2、访问index.html中的css/javascript文件;
——-1、如果直接在index.html中链接css/js文件,还是按照什么的写法,是访问不到css/js文件的;
——-2、按照上面的思路,这两个文件(css、js),还是可以用“fs”模块读取然后写到响应中去write();

这里写图片描述

目录结构:
-----public---index.html
           ---index.css
           ---index.js 
-----http.js

//demo=================================
const http = require("http");
const fs = require("fs");
const url = require("url");
http.createServer(function(req,res){
    var pathname = url.parse(req.url).pathname;
    var ext = pathname.match(/(\.[^.]+|)$/)[0];
    switch (ext){
        case ".css" :
        case ".js"  :
            fs.readFile("./public/"+req.url, function(err,data){
                res.writeHead(200,{"Content-Type":{
                    ".css" : "text/css",
                    ".js" : "application/javascript"
                }[ext]
                });
                res.write(data);
                res.end();
            })
            break;
        default :
            fs.readFile("public/index.html", function(err,data){
                res.writeHead(200,{"Content-Type":"text/html"});
                res.write(data);
                res.end();
            })
    }
}).listen(8000,"127.0.0.1")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值