美文网首页
node笔记-2.http 静态资源服务器的基本搭建

node笔记-2.http 静态资源服务器的基本搭建

作者: 柠檬树QAQ | 来源:发表于2019-12-25 22:07 被阅读0次

    http 静态资源服务器的基本搭建

    把静态的资源放在当前目录下的view文件夹下,node会到DirPath下去找你的文件

    const http = require('http')
    const fs = require('fs')
    const DirPath = './view' // 建议换成绝对路径
    // 创建服务器
    const service = http.createServer()
    service.on('request',(res,req)=>{
        let url = req.url
        // 如果是根目录 返回首页的内容
        url == '/'&&(url='/index.html')
        // 调用fs模块完成文件的读取
        fs.readFile(DirPath+url,(err,data)=>{
            if(err){
                return res.end('404 Not Found')
            }
            res.end(data)
        })
    })
    service.listen(3000,()=>{console.log('server is runing.')})
    

    相关文章

      网友评论

          本文标题:node笔记-2.http 静态资源服务器的基本搭建

          本文链接:https://www.haomeiwen.com/subject/feuhoctx.html