静态服务器 Note-FrontEnd-31

401 阅读1分钟

修改之前的静态服务器,内容包括简化不同路径的请求、错误处理、Content-Type、默认首页、最终代码。

之前的静态服务器代码很不灵活,代码如下

 console.log('有个傻子发请求过来啦!路径(带查询参数)为:' + pathWithQuery)
  if(path === '/'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/index.html')
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你访问的页面不存在`)
    response.end()
  }

一、简化不同路径的请求

不必每次访问一个文件的时候,专门为这个文件新写一段请求,代码是可以复用的,修改如下

response.statueCode = 200
response.setHeader('Content-Type','text/html;charset=utf-8')
response.write(fs.readFileSync(`public${path}`))
response.send()

二、错误处理

当访问的路径不存在时,服务器就挂了,当然不能这么脆弱,我们需要对出现错误的语句进行错误处理

let content
try{
    content = fs.readFileSync(`public${path}`)
}catch(error){
    content = '你访问的页面不存在'
    response.statusCode = 404
}

三、Content-Type

当访问不同类型的文件时,响应的请求头中的 Content-Type 也要做响应修改,我们这里使用哈希表的方式

其中,text/html 兜底

const index = filePath.lastIndexOf(".");
const suffix = filePath.substring(index);
const fileTypes = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".png": "image/png",
    ".jpg": "image/jpeg"
 };
response.setHeader(
    "Content-Type",
    `${fileTypes[suffix]} || text/html;charset=utf-8`
 );

四、默认首页

当用户访问根目录 '/' 时,我们设置成访问默认首页,即访问 '/index.html'

const filePath = path === "/" ? "/index.html" : path;

设置路径改成了 filePath,所以错误处理中的路径也要改成 filePath

五、最终代码

GitHub 链接:点击这里

console.log("有个傻子发请求过来啦!路径(带查询参数)为:" + pathWithQuery);
  // 默认首页
  response.statusCode = 200;
  const filePath = path === "/" ? "/index.html" : path;
  const index = filePath.lastIndexOf(".");
  const suffix = filePath.substring(index);
  const fileTypes = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".png": "image/png",
    ".jpg": "image/jpeg"
  };
  response.setHeader(
    "Content-Type",
    `${fileTypes[suffix]} || text/html;charset=utf-8`
  );
  let content;
  try {
    content = fs.readFileSync(`public${filePath}`);
  } catch (error) {
    content = "你访问的页面不存在";
    console.log(content);
    response.statusCode = 404;
  }
  response.write(content);
  response.end();

「资料来源:©饥人谷」