Programming

Node.js HTTP 서버로 단일 쿠키 가져 오기 및 설정

procodes 2020. 6. 12. 23:22
반응형

Node.js HTTP 서버로 단일 쿠키 가져 오기 및 설정


단일 쿠키를 설정하고 nodejs 서버 인스턴스에 대한 각 요청으로 단일 쿠키를 읽습니다. 타사 라이브러리를 가져올 필요없이 몇 줄의 코드로 수행 할 수 있습니까?

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에서 직접 위의 코드를 가져 와서 쿠키를 작성하십시오.


쿠키 가져 오기 / 설정에 대한 빠른 기능 액세스가 없으므로 다음 해킹을 생각해 냈습니다.

var http = require('http');

function parseCookies (request) {
    var list = {},
        rc = request.headers.cookie;

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

    return list;
}


http.createServer(function (request, response) {

  // To Read a Cookie
  var 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);

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

이렇게하면 모든 쿠키가 쿠키 개체에 저장되며 헤드를 작성할 때 쿠키를 설정해야합니다.


많은 node.js 개발자가하는 것처럼 익스프레스 라이브러리를 사용하는 경우 더 쉬운 방법이 있습니다. 자세한 내용은 Express.js 설명서 페이지를 확인하십시오.

위의 구문 분석 예제는 작동하지만 express는이를 처리하는 훌륭한 기능을 제공합니다.

app.use(express.cookieParser());

쿠키를 설정하려면

res.cookie('cookiename', 'cookievalue', { maxAge: 900000, httpOnly: true });

쿠키를 지우려면 :

res.clearCookie('cookiename');

RevNoah는 Express의 쿠키 파서 를 사용하는 것이 가장 좋습니다 . 그러나 그 대답은 이제 3 살이며 오래되었습니다.

Express를 사용하면 다음과 같이 쿠키를 읽을 수 있습니다

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/myapi', function(req, resp) {
   console.log(req.cookies['Your-Cookie-Name-Here']);
})

package.json적절한 최신 버전으로 대체하여 다음으로 업데이트하십시오 .

"dependencies": {
    "express": "4.12.3",
    "cookie-parser": "1.4.0"
  },

쿠키 설정 및 구문 분석과 같은 추가 작업은 여기여기에 설명 되어 있습니다.


포괄적 인 기능 세트가있는 "쿠키"npm 모듈을 사용할 수 있습니다.

https://github.com/jed/cookies의 설명서 및 예제


@Corey Hart의 답변을 향상시키면서 다음을 parseCookies()사용하여 다시 작성했습니다 .

Here's the working example:

let http = require('http');

function parseCookies(cookie) {
  let rx = /([^;=\s]*)=([^;]*)/g;
  let obj = { };
  for ( let m ; m = rx.exec(cookie) ; )
    obj[ m[1] ] = decodeURIComponent( m[2] );
  return obj;
}

function stringifyCookies(cookies) {
  let list = [ ];
  for ( [ key, value ] of Object.entries( cookies ) )
    list.push( key + '=' + encodeURIComponent( value ) );
  return list.join( '; ' );
}

http.createServer(function ( request, response ) {
  let cookies = parseCookies( request.headers.cookie );
  console.log( 'Input cookies: ', cookies );
  cookies.search = 'google';
  if ( cookies.counter )
    cookies.counter++;
  else
    cookies.counter = 1;
  console.log( 'Output cookies: ', cookies );
  response.writeHead( 200, {
    'Set-Cookie': stringifyCookies(cookies),
    'Content-Type': 'text/plain'
  } );
  response.end('Hello World\n');
} ).listen(1234);

I also note that the OP uses the http module. If the OP was using restify, he can make use of restify-cookies:

var CookieParser = require('restify-cookies');
var Restify = require('restify');
var server = Restify.createServer();
server.use(CookieParser.parse);
server.get('/', function(req, res, next){
  var cookies = req.cookies; // Gets read-only cookies from the request
  res.setCookie('my-new-cookie', 'Hi There'); // Adds a new cookie to the response
  res.send(JSON.stringify(cookies));
});
server.listen(8080);

Cookies are transfered through HTTP-Headers
You'll only have to parse the request-headers and put response-headers.


To get a cookie splitter to work with cookies that have '=' in the cookie values:

var get_cookies = function(request) {
  var cookies = {};
  request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
    var parts = cookie.match(/(.*?)=(.*)$/)
    cookies[ parts[1].trim() ] = (parts[2] || '').trim();
  });
  return cookies;
};

then to get an individual cookie:

get_cookies(request)['my_cookie']

Here's a neat copy-n-paste patch for managing cookies in node. I'll do this in CoffeeScript, for the beauty.

http = require 'http'

http.IncomingMessage::getCookie = (name) ->
  cookies = {}
  this.headers.cookie && this.headers.cookie.split(';').forEach (cookie) ->
    parts = cookie.split '='
    cookies[parts[0].trim()] = (parts[1] || '').trim()
    return

  return cookies[name] || null

http.IncomingMessage::getCookies = ->
  cookies = {}
  this.headers.cookie && this.headers.cookie.split(';').forEach (cookie) ->
    parts = cookie.split '='
    cookies[parts[0].trim()] = (parts[1] || '').trim()
    return

  return cookies

http.OutgoingMessage::setCookie = (name, value, exdays, domain, path) ->
  cookies = this.getHeader 'Set-Cookie'
  if typeof cookies isnt 'object'
    cookies = []

  exdate = new Date()
  exdate.setDate(exdate.getDate() + exdays);
  cookieText = name+'='+value+';expires='+exdate.toUTCString()+';'
  if domain
    cookieText += 'domain='+domain+';'
  if path
    cookieText += 'path='+path+';'

  cookies.push cookieText
  this.setHeader 'Set-Cookie', cookies
  return

Now you'll be able to handle cookies just as you'd expect:

server = http.createServer (request, response) ->
  #get individually
  cookieValue = request.getCookie 'testCookie'
  console.log 'testCookie\'s value is '+cookieValue

  #get altogether
  allCookies = request.getCookies()
  console.log allCookies

  #set
  response.setCookie 'newCookie', 'cookieValue', 30

  response.end 'I luvs da cookies';
  return

server.listen 8080

If you don't care what's in the cookie and you just want to use it, try this clean approach using request (a popular node module):

var request = require('request');
var j = request.jar();
var request = request.defaults({jar:j});
request('http://www.google.com', function () {
  request('http://images.google.com', function (error, response, body){
     // this request will will have the cookie which first request received
     // do stuff
  });
});

First one needs to create cookie (I have wrapped token inside cookie as an example) and then set it in response.To use the cookie in following way install cookieParser

app.use(cookieParser());

The browser will have it saved in its 'Resource' tab and will be used for every request thereafter taking the initial URL as base

var token = student.generateToken('authentication');
        res.cookie('token', token, {
            expires: new Date(Date.now() + 9999999),
            httpOnly: false
        }).status(200).send();

To get cookie from a request on the server side is easy too.You have to extract the cookie from request by calling 'cookie' property of the request object.

var token = req.cookies.token; // Retrieving Token stored in cookies

var cookie = 'your_cookie';
var cookie_value;
var i = request.headers.indexOf(cookie+'=');
if (i != -1) {
  var eq = i+cookie.length+1;
  var end = request.headers.indexOf(';', eq);
  cookie_value = request.headers.substring(eq, end == -1 ? undefined : end);
}

참고URL : https://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server

반응형