nodejs静态资源访问

    技术2026-03-31  10

    const http=require('http');//引入http模块 const url=require('url');//引入url模块 const path=require('path');//引入路径处理模块儿 const fs=require('fs');//引入处理文件的模块 const mime=require('mime');//引入mime模块 const app=http.createServer();//定义服务器 app.on('request',(req,res)=>{//监听客户端请求 // 获取用户的请求路径 let pathname=url.parse(req.url).pathname; pathname = pathname == '/' ? '/default.html' : pathname; // 将用户的请求路径转换为实际的服务器硬盘路径 let realPath=path.join(__dirname,'public'+pathname); // //通过后缀名指定mime类型 获取对应的type类型 let type=mime.getType(realPath); console.log(type) // res.end(realPath); // 读取文件 fs.readFile(realPath,(error,result)=>{ // 读取失败 if(error!=null){ // 向请求的客户端发送响应头。设置返回数据的格式以及编码格式 res.writeHead(404,{ 'content-type':'text/html;charset=utf8' }); res.end('文件读取失败!!!!!!!'); return; } // 读取成功 res.writeHead(200,{ 'content-type':type+';charset=utf8' }) res.end(result) }) }) // 监听3000端口 app.listen(3000); console.log('服务器启动成功!!')
    Processed: 0.012, SQL: 10