javascript - 使用 Node.js HTTP 服务器获取和设置单个 Cookie

标签 javascript node.js cookies httpserver

我希望能够设置一个 cookie,并在向 nodejs 服务器实例发出的每个请求中读取该单个 cookie。几行代码就能搞定,不需要拉入第三方库?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

只是尝试直接从 nodejs.org 获取上述代码,并在其中添加一个 cookie。

最佳答案

没有快速访问获取/设置 cookie 的功能,所以我想出了以下 hack:

const http = require('http');

function parseCookies (request) {
    const list = {};
    const cookieHeader = request.headers?.cookie;
    if (!cookieHeader) return list;

    cookieHeader.split(`;`).forEach(function(cookie) {
        let [ name, ...rest] = cookie.split(`=`);
        name = name?.trim();
        if (!name) return;
        const value = rest.join(`=`).trim();
        if (!value) return;
        list[name] = decodeURIComponent(value);
    });

    return list;
}

const server = http.createServer(function (request, response) {
    // To Read a Cookie
    const cookies = parseCookies(request);

    // To Write a Cookie
    response.writeHead(200, {
        "Set-Cookie": `mycookie=test`,
        "Content-Type": `text/plain`
    });

    response.end(`Hello World\n`);
}).listen(8124);

const {address, port} = server.address();
console.log(`Server running at http://${address}:${port}`);

这会将所有cookies存储到cookies对象中,需要在写head的时候设置cookies。

关于javascript - 使用 Node.js HTTP 服务器获取和设置单个 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3393854/

相关文章:

javascript - 如何使用 JSON Web token 验证从 chrome 扩展到我的应用程序的 POST 请求?

javascript - 将对象数组中的字符串转换为数字数组

javascript - 类型错误 : Converting circular structure to JSON

ios - Apple 会因为使用 cookie 而拒绝应用程序吗?

http - 如何在 Go 中删除 cookie

javascript - 使用 $in 查找中的 Mongoose 动态查询不起作用

javascript - 巴别塔配置 "strict mode"

mysql - node-mysql 一次查询多条语句

node.js - 在 heroku 中未使用 express.static 提供子目录

javascript - NextJS-getServerSideProps 中有多个 "Set-Cookie"字段?