NodeJS在特定路由上写入或删除Cookie

时间:2019-05-04 17:32:06

标签: javascript node.js cookies

我必须为大学设计一个应用程序(并且不允许使用Express或其他类似模块),我想知道如何指定编写cookie的路线。为什么?

到目前为止,我注意到cookie主要存储在域中,但是如果您在localhost:3000 /上设置cookie,该cookie也会在子路由上,但是,如果您在localhost:3000 / someroute上设置cookie,那么该cookie不会位于“ /”上。

  

那么当您在“ / someRoute”上时,如何在“ /”上设置cookie?   那么如何删除Cookie?

到目前为止,这就是我一直在写Cookie的方式

print $1,$2
  
      
  • 请注意,我问您如何在特定路线上编辑这些cookie,而不是它们如何工作
  •   

2 个答案:

答案 0 :(得分:2)

您要查找的是Path指令。

Set-Cookie: <nome-cookie>=<valor-cookie> 
Set-Cookie: <nome-cookie>=<valor-cookie>; Expires=<date>
Set-Cookie: <nome-cookie>=<valor-cookie>; Max-Age=<non-zero-digit>
Set-Cookie: <nome-cookie>=<valor-cookie>; Domain=<domain-value>
**Set-Cookie: <nome-cookie>=<valor-cookie>; Path=<path-value>**
Set-Cookie: <nome-cookie>=<valor-cookie>; Secure
Set-Cookie: <nome-cookie>=<valor-cookie>; HttpOnly

Set-Cookie: <nome-cookie>=<valor-cookie>; SameSite=Strict
Set-Cookie: <nome-cookie>=<valor-cookie>; SameSite=Lax

在您的情况下:

Set-Cookie: Path=/something;

进一步阅读:HTTP cookies

答案 1 :(得分:1)

以下是一个简单的nodejs http服务器设置,用于读取,设置和删除cookie

const http = require("http");

const PORT = process.env.PORT || 3003;

const setCookie = (res, name, value, opts) => {
    let str = name + "=" + value;

    if(opts){
        if(opts.expires){
            str += "; Expires=" + opts.expires.toUTCString();
        }
    }

    res.writeHead(200, {
        "Set-Cookie": str
    });
}

const routes = [
    {
        method: "GET",
        path: "/",
        callback: (req, res) => {
            return "hello at /";
        }
    },
    {
        method: "GET",
        path: "/set-cookie",
        callback: (req, res) => {
            setCookie(res, "mycookie", "test")
            return "Cookie set `mycookie` with value `test`";
        }
    },
    {
        method: "GET",
        path: "/get-cookie",
        callback: (req, res) => {
            return JSON.stringify(parseCookies(req));
        }
    },
    {
        method: "GET",
        path: "/delete-cookie",
        callback: (req, res) => {
            return setCookie(res, "mycookie", "test", {expires: new Date(0)});
        }
    }
];

const parseCookies = (req) => {
    const list = {};
    const cookie = req.headers.cookie;

    cookie && cookie.split(';').forEach(function( c ) {
        var parts = c.split('=');
        list[parts.shift().trim()] = decodeURI(parts.join('='));
    });

    return list;
}

const routeMatches = (original, requested) => {
    return original === requested; // basic string match without any pattern checking etc...
}

const handleRoute = (req, res) => {
    const _path = req.url;
    const _method = req.method;

    for(let i = 0; i < routes.length; i++){

        const route = routes[i];

        if(route.method === _method && routeMatches(route.path, _path)){
            return route.callback(req, res);
        }
    }
    return "404, Not Found " + _path;
};

const handleRequest = (req, res) => {
    const response = handleRoute(req, res);
    res.end(response);
};

const server = http.createServer(handleRequest);

server.listen(PORT, () => {
    console.log("Server running at http://localhost:%s", PORT);
});

handleRequest处理所有向下传递到此基本服务器的请求。

handleRoute方法是一个非常简单的解析器。此函数基本上将所有传入的请求接收到服务器,并将url与上面定义的routes数组上的已注册路由进行匹配,并通过调用callback方法返回响应。

还有其他三种帮助器方法:setCookie用于在响应头中设置cookie,parseCookie用来解析来自键值对中请求头的原始cookie,而routeMatches则用于检查提供的路径是否匹配。

/set-cookie路径只会在标题中设置一个cookie /get-cookie路径将获取Cookie列表 /delete-cookie路径将删除在/set-cookie路径中设置的cookie

一个简短的说明,您不能真正删除cookie,可以将过期时间设置为比现在更早的时间,这样会将cookie从jar中删除。

希望这会有所帮助。