Can I send a GET request with cookies in the heade

2020-07-10 07:24发布

In a browser, if I send a GET request, the request will send the cookie in the meanwhile. Now I want to simulate a GET request from Node, then how to write the code?

标签: node.js
3条回答
混吃等死
2楼-- · 2020-07-10 07:56

If you want to do it with the native http:request() method, you need to set the appropriate Set-Cookie headers (see an HTTP reference for what they should look like) in the headers member of the options argument; there are no specific methods in the native code for dealing with cookies. Refer to the source code in Mikeal's request library and or the cookieParser code in connect if you need concrete examples.

But Femi is almost certainly right: dealing with cookies is full of rather nitpicky details and you're almost always going to be better off using code that's already been written and, more importantly, tested. If you try to reinvent this particular wheel, you're likely to come up with code that seems to work most of the time, but occasionally and unpredicatably fails mysteriously.

查看更多
Root(大扎)
3楼-- · 2020-07-10 08:17

Using the marvelous request library cookies are enabled by default. You can send your own like so (taken from the Github page):

var j = request.jar()
var cookie = request.cookie('your_cookie_here')
j.add(cookie)
request({url: 'http://www.google.com', jar: j}, function () {
  request('http://images.google.com')
})
查看更多
▲ chillily
4楼-- · 2020-07-10 08:19
var jar = request.jar();
const jwtSecret = fs.readFileSync(`${__dirname}/.ssh/id_rsa`, 'utf8');
const token = jwt.sign(jwtPayload, jwtSecret, settings);
jar.setCookie(`any-name=${token}`, 'http://localhost:12345/');
const options = {
  method: 'GET',
  url: 'http://localhost:12345',
  jar,
  json: true
};
request(options, handleResponse);
查看更多
登录 后发表回答