08-Node.js学习笔记-静态资源访问

静态资源

服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如css,javaScript,image文件

动态资源

相同的请求地址不同的响应资源,这种资源就是动态资源

http://www.xxx.cn/article?id=1
http://www.xxx.cn/article?id=2

第三方模块mime下载

//mime插件:可以根据当前的请求路径分析出资源的类型,然后把类型通过返回值的方式返回给你
npm install mime
const http  = require('http');
const url = require('url');
const path = require('path');
const fs  = require('fs');
const mime = require('mime');
const app = http.createServer();
app.on('request',(req,res)=>{
    //获取用户的请求路径
    let pathname = url.parse(req.url).pathname;
    pathname=pathname=='/'?'/cc.html':pathname;
    //将用户的请求路径转换为实际的服务器硬盘路径
    let realPath = path.join(__dirname,'public'+pathname);
    let type=mime.getType(realPath)
    //读取文件
    fs.readFile(realPath,(err,result)=>{
        //如果文件读取失败
        if(err !=null){
            res.writeHead(404,{
                'content-type':'text/html;charset=utf8'
            })
            res.end('文件读取失败');
            return;
        }
        res.writeHead(200,{
            'content-type':type
        })
        res.end(result)

    })
})
app.listen(3000);
console.log('服务器启动成功')

猜你喜欢

转载自www.cnblogs.com/foreverLuckyStar/p/12072123.html