Javascript 将 cookie 作为 node.js 请求的一部分传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34859908/
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 16:58:17  来源:igfitidea点击:

Pass cookie as part of node.js request

javascriptnode.jscookiesrequest

提问by Trung Tran

I am using the requestpackage to create my server side requests. I wrote authentication middleware that checks for a cookie/session id for all requests. Therefore, is there a way I include the user's cookie as part of the request? Here is my current code:

我正在使用该request包来创建我的服务器端请求。我编写了身份验证中间件,用于检查所有请求的 cookie/会话 ID。因此,有没有办法将用户的 cookie 作为请求的一部分包含在内?这是我当前的代码:

var cookie = parseCookie.parseCookie(req.headers.cookie);

request('http://localhost:3000/users/api', function(error, response, body) {
    console.log(body); //this console.logs my login page since requests w/o valid cookies get redirected to login
    res.render('../views/admin');
});

Currently, this returns 'no cookie found' in the console. However, if I turn off my authentication middleware, the code above works as intended.

目前,这会在控制台中返回“未找到 cookie”。但是,如果我关闭身份验证中间件,上面的代码将按预期工作。

Additional info:

附加信息:

The cookie I want is the end user's cookie located on the browser. The end user's cookie is created by the app whenever the user logs in.

我想要的 cookie 是位于浏览器上的最终用户的 cookie。每当用户登录时,应用程序都会创建最终用户的 cookie。

Update - solution attempt 1:

更新 - 解决方案尝试 1:

I tried this from the documentation:

我从文档中尝试了这个:

var cookie = parseCookie.parseCookie(req.headers.cookie);
var cookieText = 'sid='+cookie;
var j = request.jar();
        var cookie = request.cookie(cookieText);
        var url = 'http://localhost:3000/users/api';
        j.setCookie(cookie, url);
        request({url: url, jar: j}, function(error, response, body) {
            request('http://localhost:3000/users/api');
        });

However, the console is still returning 'no cookie found'

但是,控制台仍然返回“未找到 cookie”

Can someone help?

有人可以帮忙吗?

Thanks in advance!

提前致谢!

回答by jfriend00

Let me explain about cookies and that will probably show you why it's hard to get the cookie you want.

让我解释一下 cookie,这可能会告诉你为什么很难得到你想要的 cookie。

  1. When your user's browser logs into http://localhost:3000, that server creates a login cookie and returns it as part of the login response.
  2. When the browser receives that cookie, it saves that cookie persistently within the browser and it associates that cookie with the http://localhost:3000domain and port.
  3. When the user again makes a request to http://localhost:3000, the browser sends all cookies it has previously saved for that particular domain and port with the request to the server.
  4. When the server receives the request, it can examine any cookies that are sent with the request.
  5. When the browser then makes a request to a different server or even the same server, but on a different port, the browser does NOT send the previously saved cookies with that request because those cookies belong to a different server and port. The browser goes to great security lengths to send cookies only to the servers that the cookies belong to. Since cookies often provide login access, you can clearly see why it's important that things like login credential cookies are not sent to servers they should not be sent to.
  1. 当您用户的浏览器登录 时http://localhost:3000,该服务器会创建一个登录 cookie 并将其作为登录响应的一部分返回。
  2. 当浏览器收到该 cookie 时,它​​会将该 cookie 永久保存在浏览器中,并将该 cookie 与http://localhost:3000域和端口相关联。
  3. 当用户再次http://localhost:3000向 发出请求时,浏览器会将其先前为该特定域和端口保存的所有 cookie 连同请求发送到服务器。
  4. 当服务器收到请求时,它可以检查随请求发送的任何 cookie。
  5. 当浏览器随后向不同的服务器或什至同一服务器发出请求,但在不同的端口上时,浏览器不会随该请求发送先前保存的 cookie,因为这些 cookie 属于不同的服务器和端口。浏览器采取了极大的安全措施,只将 cookie 发送到 cookie 所属的服务器。由于 cookie 通常提供登录访问,因此您可以清楚地看到为什么像登录凭据 cookie 之类的东西不要发送到它们不应该发送到的服务器是很重要的。

Now, on to your node.js code. You show a block of node.js code that is trying to access the same http://localhost:3000server. But, the cookies are stored in the user's browser. Your node.js code cannot get them from the browser as the browser guards them and will only reveal them when the browser itself sends a request to http://localhost:3000.

现在,转到您的 node.js 代码。您显示了一个试图访问同一http://localhost:3000服务器的 node.js 代码块。但是,cookie 存储在用户的浏览器中。您的 node.js 代码无法从浏览器获取它们,因为浏览器会保护它们,并且只会在浏览器本身向http://localhost:3000.



If you do actually have the right cookie in your node.js code, then you can set it on your request like this:

如果您的 node.js 代码中确实有正确的 cookie,那么您可以在您的请求中设置它,如下所示:

request({url: 'http://localhost:3000/users/api', headers: {Cookie: somedataHere}}, function(error, response, body) {
    console.log(body); //this console.logs my login page since requests w/o valid cookies get redirected to login
    res.render('../views/admin');
});

Relevant documentation for custom headers in the requestmodule is here.

request模块中自定义标头的相关文档在此处

回答by Trung Tran

Answer:

回答:

var cookie = parseCookie.parseCookie(req.headers.cookie);
var cookieText = 'sid='+cookie;
var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
   'User-Agent': 'request'.
   'host': 'localhost:3000',
   'cookie': cookieText //this is where you set custom cookies
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}

request(options, callback);