node.js搭建静态服务器

一、引入模块

//网络请求模块
let http = require('http');
//路径模块
let path = require('path');
//url模块
let url = require('url');
//流模块
let fs = require('fs');

二、创建服务

http.createServer((req, res) => {
    console.log(__dirname)
    console.log(path.join(__dirname, 'static'))
    staticRoot(path.join(__dirname, 'static'), req, res)
}).listen(3000)

__dirname:指的是当前路径,/xxx/demo2/bin,绝对路径
path.join(__dirname, 'static'):指的是static路径,/xxx/demo2/bin/static,绝对路径

三、解析请求和响应

function staticRoot(staticPath, req, res) {

    let pathObj = url.parse(req.url, true);
    if (pathObj.pathname === '/favicon.ico') {
        return;
    }
    //兼容http://localhost:3000/
    if (pathObj.pathname === '/') {
        pathObj.pathname += 'index.html';
    }
    //获取最终路径
    let filePath = path.join(staticPath, pathObj.pathname);

    //同步,不能处理异常情况
    //let fileContent = fs.readFileSync(filePath, "binary");
    // res.write(fileContent, "binary");
    // res.end()

    //异步可以处理异常情况,binary表示二进制流,二进制流可以传输图片,文本,视频等等
    fs.readFile(filePath, 'binary', (err, data) => {
        if (err) {
            //浏览器输入没有的资源返回404
            res.writeHead(404, 'not found');
            res.write('<h1>Not Found</h1>')
            res.end()
        } else {
            res.writeHead(200, 'ok')
            res.write(data, 'binary');
            res.end()
        }
    })
}

访问一下链接,即可请求到网页数据

file:///Users/xxx/code/code_node/demo2/bin/static/imgs/logo.png
http://localhost:3000/index.html
http://localhost:3000/
http://localhost:3000/imgs/logo.png

原理:当浏览器访问http://localhost:3000/index.html,req接受到请求信息,获取index.html字符串,将该字符串拼接在path.join(__dirname, 'static')后面,即可找到对应的文件路径,通过fs读取该文件的二进制流,传递给res,响应到浏览器,就可展示页面内容。

四、其他静态资源

a.css:

h1{
  color: red;
}

b.css:

var xhr = new XMLHttpRequest()
xhr.open('GET', '/getWeather?city=hangzhou', true)
xhr.send()
xhr.onload = function(){
  console.log(JSON.parse(xhr.responseText))
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>hello</title>
  <link rel="stylesheet" href="css/a.css">
</head>
<body>
  <h1>hello world</h1>
  <img src="imgs/logo.png" alt="">
  <form action="/search" method="POST">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit" value="search">
  </form>
  <script src="js/b.js"></script>
</body>
</html>

效果如下:

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值