📜  为什么 Node.js 使用 HTTP cookie 来发送和接收 HTTP cookie?

📅  最后修改于: 2022-05-13 01:56:35.756000             🧑  作者: Mango

为什么 Node.js 使用 HTTP cookie 来发送和接收 HTTP cookie?

HTTP协议是OSI模型应用层最重要的协议之一。该协议的主要用途是将超文本信息发送到客户端到服务器和服务器到客户端以在万维网上进行通信。但是,HTTP 协议是无状态协议,这意味着该协议无法维护任何特定客户端过去对服务器的请求。这意味着我们必须反复授权请求才能前进到 Web 应用程序的下一页。

我们如何克服这个问题?

什么是饼干?
简而言之,cookie 只是有关某些网站的文本信息。当您访问特定网站时,一些信息会保存在您的本地系统中,以便您再次访问同一网站时,该网站能够识别您并根据您的喜好向您显示结果。 Cookie 在互联网历史上已被长期使用。

示例:当您访问一个网站时,您实际上是从服务器请求该网页。对于服务器,每个请求都是唯一的请求。因此,如果您访问一百次,服务器将认为每个请求都是唯一的。由于到达服务器的请求强度很高,因此不将所有用户信息存储在服务器上是显而易见且合乎逻辑的。如果您不再访问该网站怎么办?这些信息将是多余的。因此,为了唯一地记住您,服务器会发送 cookie 以及保存在本地计算机中的响应。现在,当您下次访问同一服务器时,您将根据自己的喜好得到响应,因为服务器会识别您。

此 cookie 对每个服务器都是唯一的(由于广告,今天存在一些例外情况)。因此,您的系统中可能有许多 cookie,但服务器会识别自己的 cookie 并可以为您分析它。

HTTP Cookies:使用 HTTP Cookies 是解决问题的简单方法之一。有很多类型的 cookie 用于服务器和客户端之间的顺畅通信。最常用的 cookie 是 Session cookie。

会话 cookie:这些 cookie 存储在临时内存中,并且在特定会话之前有效,直到用户在特定网站上冲浪,然后浏览器还让我们选择是否要存储这些 cookie。会话 cookie 主要用于电子商务网站,以便在没有会话 cookie 的情况下跟踪我们的商品订单列表,在浏览特定电子商务网站的新页面后,我们的购物车将始终清空。这就是为什么在网上冲浪期间使用不同的 HTTP cookie 来跟踪我们过去的请求的原因。

Node.js如何发送和接收 cookie?

Express.js 框架使用中间件,因此可以轻松处理许多请求。同样,Express.js 支持使用中间件解析传入请求的功能。当新客户端在成功填写凭据后发出授权请求时,会向客户端发送一个包含签名 cookie 的响应头,其中包含签名格式的所有信息,并在客户端为特定会话生成一个 cookie。

当客户端第二次发出请求时,该请求包含一个签名的 cookie,其中包含该会话过去接受的所有请求信息。 Node.js 服务器使用签名密钥解析此签名 cookie,并检查该会话是否存在 cookie。如果存在,则接受传入请求,否则拒绝所有传入请求。

签名 Cookie:

安装模块:使用以下命令安装expresscookie-parser模块:

npm install express.js
npm install cookie-parser

项目结构:它将如下所示:

项目结构

文件名:index.js

Javascript
// Importing express module
const express = require("express");
 
// Importing cookie-parser module
var cookieParser = require('cookie-parser');
 
// Importing filesystem module
const fs = require("fs");
var path = require('path');
 
// Initialisation express server
const app = express();
 
// Parsing the signed cookies
app.use(cookieParser('1234567890GFG'));
function auth(req, res, next) {
 
    console.log(req.signedCookies.user)
 
    // Checking request containing signed
    //  cookies or not
    if (!req.signedCookies.user) {
 
        // Asking for authorization
        var authHeader = req.headers.authorization;
        if (!authHeader) {
            var err = new Error('You are not authenticated!');
            res.setHeader('WWW-Authenticate', 'Basic');
            err.status = 401;
            return next(err)
        }
 
        // Checking the credintials
        var auth = new Buffer.from(authHeader.split(' ')[1],
            'base64').toString().split(':');
 
        // Username and Password
        var user = auth[0];
        var pass = auth[1];
 
        if (user == 'admin' && pass == 'password') {
 
            // Sending the set-cookie header to the client side
            res.cookie("user", "admin", { signed: true })
 
            // Authorized
            next();
        } else {
 
            // Reject the authorization
            var err = new Error('You are not authenticated!');
            res.setHeader('WWW-Authenticate', 'Basic');
            err.status = 401;
            return next(err);
        }
    }
    else {
 
        // Checking whether the signed cookie exist or not
        if (req.signedCookies.user === "admin") {
            // Allowing for handling incoming request
            next()
        }
        // Rejects all the incoming requests.
        else {
            var err = new Error('You are not authenticated!');
            err.status = 401;
            return next(err);
        }
    }
}
 
// Handling authorization
app.use(auth);
app.use(express.static(path.join(__dirname, 'public')));
 
// Listening the server
app.listen((3000), () => {
    console.log("Server is Running ");
})



使用以下命令运行index.js文件:

node index.js
  • 在私人窗口中打开任何带有http://localhost:3000位置的浏览器(以避免保存密码和用户名)。地址栏附近会弹出一个弹窗。填写代码中提到的用户名和密码。

  • 如果输入的用户名和密码符合条件,则提及位置index.html将呈现在浏览器上,如下所示:

服务器的响应头:

在客户端生成的 cookie: