In Node.js, I need to catch instances where a cookie is set in a response, so I can manipulate it. I am addressing these two ways in which cookies are set:

  1. via the set-cookie HTTP header
  2. via the <meta http-equiv="Set-Cookie">

I am able to get the first one working using:

if (getProperty(responseHeaders, 'set-cookie') != null) {
    //do something
}

How would I address the second method? Do I need to scrape the HTML response, or is there a better way? If the former, how?

有帮助吗?

解决方案

I solved this by using regex on the response body:

var regexHandler = function(match, cookieValue){
    return ""; //remove the meta tag
};

responseBody = responseBody.replace(/<meta.*http-equiv=[\"']?set-cookie[\"']?.*content=[\"'](.*)[\"'].*>/gi, regexHandler);
responseBody = responseBody.replace(/<meta.*content=[\"'](.*)[\"'].*http-equiv=[\"']?set-cookie[\"']? .*>/gi, regexHandler);

其他提示

Cookies are transported as part of the HTTP headers. It is a HTTP thing, not an HTML thing.

When cookies come from the client to your server, the header field is called 'Cookie'. When you respons to the incomming request, you must always include the 'Set-Cookie' tag in your response, if you want to set or keep the cookie in the clients browser.

If you don't set the cookie, it will be removed in the clients browser.

You can look for cookies in req.header['set-cookie'], and you can set cookies the same way using the response.

There are a lot of good libraries out there which will do all of this for you. Take a look at https://github.com/jed/cookies, which works for Express, Connect and normal NodeJS :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top