当前位置:网站首页 > 技术博客 > 正文

http请求和响应的全过程



//静态资源访问 const http = require('http'); const url = require('url'); const path = require('path'); const fs = require('fs'); //mime这个第三方模块的功能是根据当前的请求路径,分析出这个资源的类型,通过返回值的方式返回资源类型。 const mime = require('mime'); const app = http.createServer(); //监听服务器 app.on('request',(req,res)=>{ //获取用户请求路径 let pathname = url.parse(req.url).pathname pathname = pathname =='/'? '/index.html': pathname //将用户的请求路径转换为实际的服务器硬盘路径 let realpath = path.join(__dirname,'public'+pathname) console.log(realpath) let type = mime.getType(realpath) // console.log(type);  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 }) res.end(result) }) }); app.listen(80); console.log('服务器启动成功!')

版权声明


相关文章:

  • python简单的新手项目2025-09-29 18:01:03
  • 电驴最新服务器列表 20202025-09-29 18:01:03
  • 班知达藏文输入法2025-09-29 18:01:03
  • ftp上传工具怎么用2025-09-29 18:01:03
  • js 注释规范2025-09-29 18:01:03
  • centos版本越高越好吗2025-09-29 18:01:03
  • Delphi软件2025-09-29 18:01:03
  • 数据库开发工具哪种好2025-09-29 18:01:03
  • green 数据库2025-09-29 18:01:03
  • php缓存技术的多种实现方法西西php技术博客2025-09-29 18:01:03