最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

從零開始學(xué)習(xí)Node.js系列教程之設(shè)置HTTP頭的方法示例

 更新時間:2017年04月13日 15:07:14   作者:MIN飛翔  
這篇文章主要介紹了Node.js設(shè)置HTTP頭的方法,詳細分析了常見HTTP頭的功能、原理及相關(guān)設(shè)置操作技巧,需要的朋友可以參考下

本文實例講述了Node.js設(shè)置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 服務(wù)器發(fā)送到客戶端

文件擴展名不足以完全恰當?shù)臉俗R文件類型,而且文件擴展名沒有標準,于是,人們設(shè)計了Content-Type頭和整個MIME類型標準來作為數(shù)據(jù)類型的表示系統(tǒng)。

對于某些應(yīng)用,特別是一些處理固定數(shù)據(jù)的小型應(yīng)用,我們可以精準的知道該使用哪一種Content-Type頭,因為應(yīng)用發(fā)送的數(shù)據(jù)是特定已知的。然而staticHandler能發(fā)送任何文件,通常不知道該使用哪種Content-Type。通過匹配文件擴展名列表和Content-Type可以解決這個問題,但是這個方案不完美。最好的實踐方案是使用一個外部的配置文件,它通常由操作系統(tǒng)提供。

MIME npm包使用了Apache項目的mime.types文件,該文件包含超過600個Content-Type的有關(guān)數(shù)據(jù),如果有需要,mime模塊也支持添加自定義的MIME類型。

npm install mime

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

一些相關(guān)的HTTP頭:

Content-Encoding 數(shù)據(jù)被編碼時使用,例如gzip
Content-Language 內(nèi)容中使用的語言
Content-Length 字節(jié)數(shù)
Content-Location 能取到數(shù)據(jù)的一個候補位置
Content-MD5 內(nèi)容主題的MD5校驗和

HTTP協(xié)議是無狀態(tài)的,意味著web服務(wù)器不能辨認不同的請求發(fā)送端?,F(xiàn)在普遍的做法是,服務(wù)器發(fā)送cookie到客戶端瀏覽器,cookie中定義了登陸用戶的身份,對于每一次請求,web瀏覽器都會發(fā)送對應(yīng)所訪問網(wǎng)站的cookie。

發(fā)送cookie時,我們應(yīng)以如下方式為Set-Cookie或Set-Cookie2頭設(shè)一個值:

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

/*
 Basic Server的核心模塊會創(chuàng)建一個HTTP服務(wù)器對象,附加Basic Server上用于檢查請求,然后給予適當響應(yīng)的功能
 Basic Server可以通過判斷Host頭部匹配的容器對象響應(yīng)來自多個域名的請求
 */
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數(shù)組以查找cookie和host頭部,因為這兩個字段對請求的分派都很重要
//這個函數(shù)在每一個HTTP請求到達時都會被調(diào)用
//還有很多其他的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;
    }
    //提取瀏覽器發(fā)送的cookie
    if (hname.toLowerCase() === "cookie"){
      req.basicServer.cookies.push(hval);
    }
  }
}
//查找匹配的容器,分派請求到對應(yīng)的容器中
//這個函數(shù)在每一個HTTP請求到達時都會被調(diào)用
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

//用于處理文件系統(tǒng)內(nèi)的文件,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以/結(jié)尾
    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

//這個處理函數(shù)處理對favicon.ico的請求
//MIME模塊根據(jù)給出的圖標文件確定正確的MIME類型,網(wǎng)站圖標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跳轉(zhuǎn)到較長的URL
 實現(xiàn)這兩種情況,我們需要在HTTP響應(yīng)中發(fā)送301(永久移除)或者302(臨時移除)狀態(tài)碼,并且指定location頭信息。有了這個組合
 信號,web瀏覽器就知道要跳轉(zhuǎn)到另一個web位置了
 */
//地址http://localhost:3000/l/ex1 會跳轉(zhuǎn)到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程序設(shè)計有所幫助。

相關(guān)文章

  • Node.js?Webpack常見的模式詳解

    Node.js?Webpack常見的模式詳解

    這篇文章主要介紹了Node.js?Webpack常見的模式,Webpack的另一個核心是Plugin?,Plugin是可以用于執(zhí)行更加廣泛的任務(wù)如打包優(yōu)化資源管理?環(huán)境變量注入等,需要的朋友可以參考下
    2022-10-10
  • node創(chuàng)建Vue項目步驟詳解

    node創(chuàng)建Vue項目步驟詳解

    在本篇文章里小編給大家整理的是關(guān)于node創(chuàng)建Vue項目步驟詳解內(nèi)容,需要的朋友們可以學(xué)習(xí)下。
    2020-03-03
  • node跨域轉(zhuǎn)發(fā) express+http-proxy-middleware的使用

    node跨域轉(zhuǎn)發(fā) express+http-proxy-middleware的使用

    這篇文章主要介紹了node跨域轉(zhuǎn)發(fā) express+http-proxy-middleware的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • Node.JS 循環(huán)遞歸復(fù)制文件夾目錄及其子文件夾下的所有文件

    Node.JS 循環(huán)遞歸復(fù)制文件夾目錄及其子文件夾下的所有文件

    在Node.js中,要實現(xiàn)目錄文件夾的循環(huán)遞歸復(fù)制也非常簡單,使用fs模塊即可,僅需幾行,而且性能也不錯,我們先來實現(xiàn)文件的復(fù)制,需要的朋友可以參考下
    2017-09-09
  • 實時通信WebSocket的原理和工作過程

    實時通信WebSocket的原理和工作過程

    WebSocket持久連接使得服務(wù)器可以主動向客戶端推送數(shù)據(jù),而不需要等待客戶端的請求,是一種專門設(shè)計用于實現(xiàn)持久連接的協(xié)議,WebSocket的持久連接特性使其成為實時性要求高的應(yīng)用的理想選擇,如在線聊天、實時游戲、數(shù)據(jù)監(jiān)控等
    2023-12-12
  • node.js操作mysql簡單實例

    node.js操作mysql簡單實例

    本文給大家介紹了nodejs 連接Mysql相關(guān)操作的示例代碼,主要用到的是sql語句,都是比較基礎(chǔ)的。
    2017-05-05
  • 在NPM發(fā)布自己造的輪子的方法步驟

    在NPM發(fā)布自己造的輪子的方法步驟

    這篇文章主要介紹了在NPM發(fā)布自己造的輪子的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-03-03
  • 史上無敵詳細的Node.Js環(huán)境搭建步驟記錄

    史上無敵詳細的Node.Js環(huán)境搭建步驟記錄

    Node.js是一個事件驅(qū)動I/O服務(wù)端JavaScript環(huán)境,由于其擁有異步非阻塞、環(huán)境搭建簡單、實踐應(yīng)用快等特性,使得其在新一代編程開發(fā)中更為流行,下面這篇文章主要給大家介紹了關(guān)于Node.Js環(huán)境搭建步驟記錄的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • 使用Node.js實現(xiàn)一個多人游戲服務(wù)器引擎

    使用Node.js實現(xiàn)一個多人游戲服務(wù)器引擎

    這篇文章主要給大家介紹了關(guān)于如何使用Node.js實現(xiàn)一個多人游戲服務(wù)器引擎的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者使用Node.js具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Node.js之IP地址和端口號問題

    Node.js之IP地址和端口號問題

    這篇文章主要介紹了Node.js之IP地址和端口號問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11

最新評論

商洛市| 景德镇市| 仙游县| 邓州市| 湘乡市| 井陉县| 永德县| 溆浦县| 堆龙德庆县| 阳江市| 盖州市| 繁昌县| 赣州市| 宜宾县| 东港市| 克东县| 个旧市| 大竹县| 水城县| 双桥区| 特克斯县| 蓝田县| 澄城县| 敦化市| 通山县| 临泽县| 策勒县| 额济纳旗| 图片| 秦安县| 老河口市| 那曲县| 剑川县| 湟源县| 平利县| 娱乐| 平谷区| 永安市| 邻水| 邢台市| 汉源县|