正确设置牛仔饼干

时间:2017-03-06 14:16:29

标签: cookies erlang cowboy

在牛仔中设置Cookie非常简单 https://ninenines.eu/docs/en/cowboy/2.0/guide/cookies/

但是当我使用这种方法设置cookie时

init(Req0, Opts) ->     
    Method = cowboy_req:method(Req0),   
    {ok, Body0,    _} = cowboy_req:read_urlencoded_body(Req0), 
    {ok, RiakPid} = riakc_pb_socket:start("127.0.0.1", 8087), 
    Req = handle(Method,    Body0, Req0, RiakPid),     
    {ok, Body, _} = cowboy_req:read_body(Req),  
    erlang:display(Req), %    here I also check request    
    {ok,Req, Opts}.

% post
handle(<<"POST">>, Body, Req0, RiakPid) ->
    SessionID = "blablabla",
    Req = cowboy_req:set_resp_cookie(<<"token">>, SessionID, Req0),
    erlang:display(Req) %here I check request
    Req;

% get. Here I should successfully get token in cookies
handle(<<"GET">>, Body, Req0, RiakPid) ->   
    Cookies = cowboy_req:parse_cookies(Req0),   
    {_, Token} = lists:keyfind(<<"token">>, 1, Cookies), % here is when i fail to get    cookie by key     
    erlang:display(Token), 
    Req0;

并使用erlang:display(Req)获取请求:

headers=>#{
<<"accept">>=><<"*/*">>
<<"accept-encoding">>=><<"gzip, deflate, br">>
<<"accept-language">>=><<"en-GB,en-US;q=0.8,en;q=0.6">>
<<"connection">>=><<"keep-alive">>
<<"content-length">>=><<"24">>
<<"content-type">>=><<"application/x-www-form-urlencoded">>
<<"cookie">>=><<"user=\"2|1:0|10:1487346656|4:user|4:Mw==|ba24da6f51c92ad05e278f218d15d2cda8ed9e7e3b800dcf39a244de5ecfff37\"">>
<<"host">>=><<"localhost:2939">>
<<"origin">>=><<"chrome-extension://eelcnbccaccipfolokglfhhmapdchbfg">>
<<"user-agent">>=><<"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36">>}
host=><<"localhost">>
host_info=>undefined,method=><<"POST">>
path=><<"/login">>
path_info=>undefined
peer=>{{127,0,0,1},53362}
pid=><0.4104.0>,port=>2939,qs=><<>>
ref=>my_http_listener
resp_cookies=>#{<<"token">>=>[<<"token">>,<<"=">>,"blablabla",<<"; Version=1">>,<<>>,<<>>,<<>>,<<>>,<<>>]}
scheme=><<"http">>,streamid=>1,version=>'HTTP/1.1'}

所以我设置标题,而不是Cookie。

如何设置真正的Cookie?

像是

<<"cookie">>=>
<<"user=\"2|1:0|10:1487346656|4:user|4:Mw==|ba24da6f51c92ad05e278f218d15d2cda8ed9e7e3b800dcf39a244de5ecfff37\"">>
<<"token=\"blablabla\"">>

1 个答案:

答案 0 :(得分:0)

这是正确的代码

% post
handle(<<"POST">>, Body, Req0, RiakPid) ->
    SessionID = "blablabla",
    Req1 = cowboy_req:set_resp_cookie(<<"token">>, SessionID, Req0),
    erlang:display(Req1) %here I check request
    Req = cowboy_req:reply(200, Req1), % We should always pass correct Request
    Req;

重点是:当一个人与Request合作时,他也应该关注请求及其状态。当您结束Request(Req = cowboy_req:reply(200,Req1))时,您的resp_cookies记录将传递给cookie。否则请求不完整