我希望能够设置一个 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。