本文实例讲述了Node.js设置HTTP头的方法。分享给大家供大家参考,具体如下:

server.js

//basic server的配置文件
var port = 3000;
var server = require('./basicserver').createServer();
server.useFavIcon("localhost", "./docroot/favicon.png");
server.addContainer(".*", "/l/(.*)$", require('./redirector'), {})
server.docroot("localhost", "/", "./docroot");
//server.useFavIcon("127.0.0.1", "./docroot/favicon.png");
//server.docroot("127.0.0.1", "/", "./docroot");
server.listen(port);

basicserver.js

Response Header 服务器发送到客户端

文件扩展名不足以完全恰当的标识文件类型,而且文件扩展名没有标准,于是,人们设计了Content-Type头和整个MIME类型标准来作为数据类型的表示系统。

对于某些应用,特别是一些处理固定数据的小型应用,我们可以精准的知道该使用哪一种Content-Type头,因为应用发送的数据是特定已知的。然而staticHandler能发送任何文件,通常不知道该使用哪种Content-Type。通过匹配文件扩展名列表和Content-Type可以解决这个问题,但是这个方案不完美。最好的实践方案是使用一个外部的配置文件,它通常由操作系统提供。

MIME npm包使用了Apache项目的mime.types文件,该文件包含超过600个Content-Type的有关数据,如果有需要,mime模块也支持添加自定义的MIME类型。

npm install mime

var mime = require('mime');
var mimeType = mime.lookup('image.gif'); //==> image/gif
res.setHeader('Content-Type', mimeType);

一些相关的HTTP头:

Content-Encoding 数据被编码时使用,例如gzip
Content-Language 内容中使用的语言
Content-Length 字节数
Content-Location 能取到数据的一个候补位置
Content-MD5 内容主题的MD5校验和

HTTP协议是无状态的,意味着web服务器不能辨认不同的请求发送端。现在普遍的做法是,服务器发送cookie到客户端浏览器,cookie中定义了登陆用户的身份,对于每一次请求,web浏览器都会发送对应所访问网站的cookie。

发送cookie时,我们应以如下方式为Set-Cookie或Set-Cookie2头设一个值:

res.setHeader('Set-Cookie2', ..cookie value..);

/*
 Basic Server的核心模块会创建一个HTTP服务器对象,附加Basic Server上用于检查请求,然后给予适当响应的功能
 Basic Server可以通过判断Host头部匹配的容器对象响应来自多个域名的请求
 */
var http = require('http');
var url = require('url');
exports.createServer = function(){
  var htserver = http.createServer(function(req, res){
    req.basicServer = {urlparsed: url.parse(req.url, true)};
    processHeaders(req, res);
    dispatchToContainer(htserver, req, res);
  });
  htserver.basicServer = {containers: []};
  htserver.addContainer = function(host, path, module, options){
    if (lookupContainer(htserver, host, path) != undefined){
      throw new Error("Already mapped "   host   "/"   path);
    }
    htserver.basicServer.containers.push({host: host, path: path, module: module, options: options});
    return this;
  }
  htserver.useFavIcon = function(host, path){
    return this.addContainer(host, "/favicon.ico", require('./faviconHandler'), {iconPath: path});
  }
  htserver.docroot = function(host, path, rootPath){
    return this.addContainer(host, path, require('./staticHandler'), {docroot: rootPath});
  }
  return htserver;
}
var lookupContainer = function(htserver, host, path){
  for (var i = 0; i < htserver.basicServer.containers.length; i  ){
    var container = htserver.basicServer.containers[i];
    var hostMatches = host.toLowerCase().match(container.host);
    var pathMatches = path.match(container.path);
    if (hostMatches !== null && pathMatches !== null){
      return {container: container, host: hostMatches, path: pathMatches};
    }
  }
  return undefined;
}
//用于搜索req.headers数组以查找cookie和host头部,因为这两个字段对请求的分派都很重要
//这个函数在每一个HTTP请求到达时都会被调用
//还有很多其他的HTTP头部字段(Accept Accept-Encoding Accept-Language User-Agent)
var processHeaders = function(req, res){
  req.basicServer.cookies = [];
  var keys = Object.keys(req.headers);
  for (var i = 0; i < keys.length; i  ){
    var hname = keys[i];
    var hval = req.headers[hname];
    if (hname.toLowerCase() === "host"){
      req.basicServer.host = hval;
    }
    //提取浏览器发送的cookie
    if (hname.toLowerCase() === "cookie"){
      req.basicServer.cookies.push(hval);
    }
  }
}
//查找匹配的容器,分派请求到对应的容器中
//这个函数在每一个HTTP请求到达时都会被调用
var dispatchToContainer = function(htserver, req, res){
  var container = lookupContainer(htserver, req.basicServer.host, req.basicServer.urlparsed.pathname);
  if (container !== undefined){
    req.basicServer.hostMatches = container.host;
    req.basicServer.pathMatches = container.path;
    req.basicServer.container = container.container;
    container.container.module.handle(req, res);
  }else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end("no handler found for "   req.basicServer.host   "/"   req.basicServer.urlparsed);
  }
}

staticHandler.js

//用于处理文件系统内的文件,docroot选项指被存放文件所在文件夹的路径,读取该目录下的指定文件
var fs = require('fs');
var mime = require('mime');
var sys = require('sys');
exports.handle = function(req, res){
  if (req.method !== "GET"){
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end("invalid method "   req.method);
  } else {
    var fname = req.basicServer.container.options.docroot   req.basicServer.urlparsed.pathname;
    if (fname.match(/\/$/)) fname  = "index.html"; //如果URL以/结尾
    fs.stat(fname, function(err, stats){
      if (err){
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end("file "   fname   " not found "   err);
      } else {
        fs.readFile(fname, function(err, buf){
          if (err){
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end("file "   fname   " not readable "   err);
          } else {
            res.writeHead(200, {'Content-Type': mime.lookup(fname),
              'Content-Length': buf.length});
            res.end(buf);
          }
        });
      }
    });
  }
}

faviconHandler.js

//这个处理函数处理对favicon.ico的请求
//MIME模块根据给出的图标文件确定正确的MIME类型,网站图标favicon可以是任何类型的图片,但是我们必须要告诉浏览器是哪个类型
//MIME模块,用于生成正确的Content-Type头
var fs = require('fs');
var mime = require('mime');
exports.handle = function(req, res){
  if (req.method !== "GET"){
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end("invalid method "   req.method);
  } else if (req.basicServer.container.options.iconPath !== undefined){
    fs.readFile(req.basicServer.container.options.iconPath, function(err, buf){
      if (err){
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end(req.basicServer.container.options.iconPath   "not found");
      } else {
        res.writeHead(200, {'Content-Type': mime.lookup(req.basicServer.container.options.iconPath),
        'Content-Length': buf.length});
        res.end(buf);
      }
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end("no favicon");
  }
}

redirector.js

/*
 把一个域的请求重定向到另一个上,例如将www.example.com重定向到example.com上,或者使用简短的URL跳转到较长的URL
 实现这两种情况,我们需要在HTTP响应中发送301(永久移除)或者302(临时移除)状态码,并且指定location头信息。有了这个组合
 信号,web浏览器就知道要跳转到另一个web位置了
 */
//地址http://localhost:3000/l/ex1 会跳转到http://example1.com
var util = require('util');
var code2url = {'ex1': 'http://example1.com', 'ex2': "http://example2.com"};
var notFound = function(req, res){
  res.writeHead(404, {'Content-Type': 'text/plain'});
  res.end("no matching redirect code found for "   req.basicServer.host   "/"   req.basicServer.urlparsed.pathname);
}
exports.handle = function(req, res){
  if (req.basicServer.pathMatches[1]){
    var code = req.basicServer.pathMatches[1];
    if (code2url[code]){
      var url = code2url[code];
      res.writeHead(302, {'Location': url});
      res.end();
    } else {
      notFound(req, res);
    }
  } else {
    notFound(req, res);
  }
}

docroot目录下:有favicon.png

index.html

<html>
<head>
</head>
<body>
  <h1>Index</h1>
  <p>this is a index html.</p>
</body>
</html>

希望本文所述对大家nodejs程序设计有所帮助。

从零开始学习Node.js系列教程之设置HTTP头的方法示例的更多相关文章

  1. CentOS 8.2服务器上安装最新版Node.js的方法

    这篇文章主要介绍了CentOS 8.2服务器上安装最新版Node.js的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  2. node.js三个步骤实现一个服务器及Express包使用

    这篇文章主要介绍了node.js三个步骤实现一个服务器及Express包使用,文章通过新建一个文件展开全文内容,具有一定的参考价值,需要的小伙伴可以参考一下

  3. Node.js调试技术总结分享

    Node.js是一个可以快速构建网络服务及应用的平台。该平台的构建是基于Chrome's JavaScript runtime,也就是说,实际上它是对Google V8引擎(应用于Google Chrome浏览器)进行了封装。 今天介绍Node.js调式目前有几种技术,需要的朋友可以参考下。

  4. node.js实现http服务器与浏览器之间的内容缓存操作示例

    这篇文章主要介绍了node.js实现http服务器与浏览器之间的内容缓存操作,结合实例形式分析了node.js http服务器与浏览器之间的内容缓存原理与具体实现技巧,需要的朋友可以参考下

  5. 教你如何使用node.js制作代理服务器

    本文介绍了如何使用node.js制作代理服务器,图文并茂,十分的详细,代码很简洁易懂,这里推荐给大家。

  6. node.js中的fs.openSync方法使用说明

    这篇文章主要介绍了node.js中的fs.openSync方法使用说明,本文介绍了fs.openSync方法说明、语法、接收参数、使用实例和实现源码,需要的朋友可以参考下

  7. Node.js+ELK日志规范的实现

    这篇文章主要介绍了Node.js+ELK日志规范的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  8. node.js爬虫框架node-crawler初体验

    这篇文章主要介绍了node.js爬虫框架node-crawler的相关资料,帮助大家利用node.js进行爬虫,感兴趣的朋友可以了解下

  9. node.js中的fs.existsSync方法使用说明

    这篇文章主要介绍了node.js中的fs.existsSync方法使用说明,本文介绍了fs.existsSync方法说明、语法、接收参数、使用实例和实现源码,需要的朋友可以参考下

  10. 说说如何利用 Node.js 代理解决跨域问题

    这篇文章主要介绍了Node.js代理解决跨域问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

随机推荐

  1. Error: Cannot find module ‘node:util‘问题解决

    控制台 安装 Vue-Cli 最后一步出现 Error: Cannot find module 'node:util' 问题解决方案1.问题C:\Windows\System32>cnpm install -g @vue/cli@4.0.3internal/modules/cjs/loader.js:638 throw err; &nbs

  2. yarn的安装和使用(全网最详细)

    一、yarn的简介:Yarn是facebook发布的一款取代npm的包管理工具。二、yarn的特点:速度超快。Yarn 缓存了每个下载过的包,所以再次使用时无需重复下载。 同时利用并行下载以最大化资源利用率,因此安装速度更快。超级安全。在执行代码之前,Yarn 会通过算法校验每个安装包的完整性。超级可靠。使用详细、简洁的锁文件格式和明确的安装算法,Yarn 能够保证在不同系统上无差异的工作。三、y

  3. 前端环境 本机可切换node多版本 问题源头是node使用的高版本

    前言投降投降 重头再来 重装环境 也就分分钟的事 偏要折腾 这下好了1天了 还没折腾出来问题的源头是node 使用的高版本 方案那就用 本机可切换多版本最终问题是因为nodejs的版本太高,导致的node-sass不兼容问题,我的node是v16.14.0的版本,项目中用了"node-sass": "^4.7.2"版本,无法匹配当前的node版本根据文章的提

  4. nodejs模块学习之connect解析

    这篇文章主要介绍了nodejs模块学习之connect解析,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  5. nodejs npm package.json中文文档

    这篇文章主要介绍了nodejs npm package.json中文文档,本文档中描述的很多行为都受npm-config(7)的影响,需要的朋友可以参考下

  6. 详解koa2学习中使用 async 、await、promise解决异步的问题

    这篇文章主要介绍了详解koa2学习中使用 async 、await、promise解决异步的问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  7. Node.js编写爬虫的基本思路及抓取百度图片的实例分享

    这篇文章主要介绍了Node.js编写爬虫的基本思路及抓取百度图片的实例分享,其中作者提到了需要特别注意GBK转码的转码问题,需要的朋友可以参考下

  8. CentOS 8.2服务器上安装最新版Node.js的方法

    这篇文章主要介绍了CentOS 8.2服务器上安装最新版Node.js的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  9. node.js三个步骤实现一个服务器及Express包使用

    这篇文章主要介绍了node.js三个步骤实现一个服务器及Express包使用,文章通过新建一个文件展开全文内容,具有一定的参考价值,需要的小伙伴可以参考一下

  10. node下使用UglifyJS压缩合并JS文件的方法

    下面小编就为大家分享一篇node下使用UglifyJS压缩合并JS文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

返回
顶部