본문 바로가기

개발/NODE

Node Express를 이용한 Cookie Set

express 4.x API Reference 참고- http://expressjs.com/en/4x/api.html


0. Header Cookie

res.append(field [, value])

res.append() is supported by Express v4.11.0+

Appends the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value. The value parameter can be a string or an array.

Note: calling res.set() after res.append() will reset the previously-set header value.

res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
res.append('Warning', '199 Miscellaneous warning');

위에처럼 Set-Cookie로 쿠키 처리 가능


1. request cookie

req.cookies

When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

// Cookie: name=tj
req.cookies.name
// => "tj"

For more information, issues, or concerns, see cookie-parser.


2. response cookie

res.cookie(name, value [, options])

Sets cookie name to value. The value parameter may be a string or object converted to JSON.

The options parameter is an object that can have the following properties.

Property Type Description
domain String Domain name for the cookie. Defaults to the domain name of the app.
encode Function A synchronous function used for cookie value encoding. Defaults to encodeURIComponent.
expires Date Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.
httpOnly Boolean Flags the cookie to be accessible only by the web server.
maxAge String Convenient option for setting the expiry time relative to the current time in milliseconds.
path String Path for the cookie. Defaults to “/”.
secure Boolean Marks the cookie to be used with HTTPS only.
signed Boolean Indicates if the cookie should be signed.

All res.cookie() does is set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.

For example:

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });

The encode option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.

Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.

//Default encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com',{domain:'example.com'});
// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'

//Custom encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com',{domain:'example.com', encode: String});
// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'

The maxAge option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.

res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true });

You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.

res.cookie('cart', { items: [1,2,3] });
res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });

When using cookie-parser middleware, this method also supports signed cookies. Simply include the signed option set to true. Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.

res.cookie('name', 'tobi', { signed: true });

Later you may access this value through the req.signedCookie object.

res.clearCookie(name [, options])

Clears the cookie specified by name. For details about the options object, see res.cookie().

res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });

3. Test Cookie


version
node : 4.2.3

npm : 3.7.3


3.1. node express 4.0 이상 설치.

3.2. cookie-parser 설치. (express 4.x부터 미들웨어 분리)

3.3. 소스 코드 작성

 

3.4. 결과

 

우선 작성해둔 node server를 실행합니다.

그리고 해당 node server로 호출을 합니다.

 

당연히 처음 호출시 request로 들어오는 cookie는 없습니다.

하지만 한번 호출로 set cookie를 했기 때문에 브라우저 쿠키에는 cookie가 있을겁니다.

 

크롬에 쿠키가 해당 도메인으로 저장되었군요.

cookie_key1, cookie_key2 각각 해당 도메인으로 남겨졌습니다.

그럼 다시 한번 node server로 호출을 해보겠습니다.

 

해당 도메인의 cookie 데이터가 들어왔네요.

여기서 cookie 테스트를 마칩니다.


 

잘못된 정보는 바로 지적해 주세요.