Javascript NodeJS 和 HTTP 客户端 - 是否支持 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2615677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:09:41  来源:igfitidea点击:

NodeJS and HTTP Client - Are cookies supported?

javascripthttpnode.js

提问by RadiantHex

NodeJSis a fantastic tool and blazing fast.

NodeJS是一个很棒的工具,而且速度非常快。

I'm wondering if HTTPClient supports cookiesand if can be used in order to simulate very basic browser behaviour!

我想知道 HTTPClient 是否支持cookie以及是否可以用来模拟非常基本的浏览器行为



Help would be very much appreciated! =)

非常感谢您的帮助!=)



EDIT:

编辑:

Found this: node-httpclient(seems useful!) not working!

发现这个:node-httpclient(似乎很有用!)不工作!

采纳答案by Kuroki Kaze

Just get cookies from Set-Cookieparam in response headers and send them back with future requests. Should not be hard.

只需从Set-Cookie响应头中的 param获取 cookie,然后将它们与未来的请求一起发送回去。应该不难。

回答by isaacs

Short answer: no. And it's not so great.

简短的回答:没有。它不是那么好。

I implemented this as part of npm so that I could download tarballs from github. Here's the code that does that: https://github.com/isaacs/npm/blob/master/lib/utils/fetch.js#L96-100

我将此作为 npm 的一部分实现,以便我可以从 github 下载 tarball。这是执行此操作的代码:https: //github.com/isaacs/npm/blob/master/lib/utils/fetch.js#L96-100

var cookie = get(response.headers, "Set-Cookie")
if (cookie) {
  cookie = (cookie + "").split(";").shift()
  set(opts.headers, "Cookie", cookie)
}

The file's got a lot of npm-specific stuff (log, set, etc.) but it should show you the general idea. Basically, I'm collecting the cookies so that I can send them back on the next request when I get redirected.

该文件有很多特定于 npm 的内容(日志、设置等),但它应该向您展示总体思路。基本上,我正在收集 cookie,以便在我被重定向时可以在下一个请求时将它们发回。

I've talked with Mikeal Rogers about adding this kind of functionality to his "request" util, complete with supporting a filesystem-backed cookiejar, but it's really pretty tricky. You have to keep track of which domains to send the cookies to, and so on.

我已经与 Mikeal Rogers 讨论过将这种功能添加到他的“请求”实用程序中,并支持文件系统支持的 cookiejar,但这确实非常棘手。您必须跟踪要将 cookie 发送到哪些域,等等。

This will likely never be included in node directly, for that reason. But watch for developments in userspace.

出于这个原因,这可能永远不会直接包含在节点中。但要注意用户空间的发展。

EDIT: This is now supported by default in Request.

编辑:现在在请求中默认支持。

回答by Martin Cleaver

If you are looking to do cookies client side you can use https://github.com/mikeal/request

如果您正在寻找做 cookie 客户端,您可以使用https://github.com/mikeal/request

M.

M。

回答by revskill

The code below demonstrates using cookie from server side, here's a demo API server that parse cookies from a http client and check the cookie hash:

下面的代码演示了从服务器端使用 cookie,这是一个演示 API 服务器,它解析来自 http 客户端的 cookie 并检查 cookie 哈希:

var express = require("express"),
app     = express(),
hbs = require('hbs'),
mongoose = require('mongoose'),
port    = parseInt(process.env.PORT, 10) || 4568;

app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public_api')); 
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.get('/api', function (req, res) {
    var cookies = {};
    req.headers.cookie && req.headers.cookie.split(';').forEach(function( cookie ) {
        var parts = cookie.split('=');
        cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    });
    if (!cookies['testcookie']) {
        console.log('First request');
        res.cookie('testcookie','testvaluecookie',{ maxAge: 900000, httpOnly: true });
        res.end('FirstRequest');
   } else {
        console.log(cookies['testcookie']);
        res.end(cookies['testcookie']);
   }
}); 

app.listen(port);

On the client side, just make a normal request to the server api above, i'm using request module, it by default transfers cookie for each request.

在客户端,只需向上面的服务器 api 发出正常请求,我正在使用请求模块,它默认为每个请求传输 cookie。

request(options, function(err, response, body) {    
    console.log(util.inspect(response.headers));
    res.render("index.html", {layout: false,user: {
        username: req.session.user + body
    }});
});

回答by dgo.a

Zombie.jsis another choice if you want browser-like behaviour. It "maintains state across requests: history, cookies, HTML5 local and session stroage, etc.". More info on zombie's cookie api: http://zombie.labnotes.org/API

如果您想要类似浏览器的行为,Zombie.js是另一种选择。它“跨请求维护状态:历史、cookie、HTML5 本地和会话存储等”。有关僵尸 cookie api 的更多信息:http: //zombie.labnotes.org/API

There is also PhantomJSand PhantomJS-based frameworks, like CasperJS.

还有PhantomJS基于 PhantomJS 的框架,比如CasperJS

回答by Domi

A feature-complete solution for cookies

功能完备的 cookie 解决方案

The self-made solutions proposed in the other answers here don't cover a lot of special cases, can easily break and lack a lot of standard features, such as persistence.

这里其他答案中提出的自制解决方案没有涵盖很多特殊情况,很容易崩溃并且缺乏很多标准功能,例如持久性。

As mentioned by isaacs, the requestmodule now has true cookie support. They provide examples with cookies on their Github page. The examples explain how to enable cookie support by adding a "tough-cookie" cookie jarto your request.

正如isaacs提到的请求模块现在具有真正的 cookie 支持。他们在 Github 页面上提供了带有 cookie 的示例。这些示例解释了如何通过向您的请求添加“tough-cookie”cookie jar来启用 cookie 支持。

NOTE: A cookie jar contains and helps you manage your cookies.

注意:cookie jar 包含并帮助您管理您的 cookie。

To quote their Readme(as of April 2015):

引用他们的自述文件(截至 2015 年 4 月):

Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set jarto true(either in defaults or options) and install tough-cookie.

默认情况下禁用 Cookie(否则,它们将在后续请求中使用)。要启用 cookie,请设置jartrue(在默认值或选项中)并安装hard-cookie

The cookie management is provided through the tough-cookie module. It is a stable, rather feature-complete cookie management tool that implements the "HTTP State Management Mechanism" - RFC 6265. It even offers a variety of options to persist (store) cookies, using a cookie store.

cookie 管理是通过tough-cookie 模块提供的。它是一个稳定的、功能完备的 cookie 管理工具,它实现了“HTTP 状态管理机制”- RFC 6265。它甚至提供了多种选项来使用cookie store来持久化(存储)cookie 。