节点js从302重定向获取Cookie

时间:2018-07-24 09:55:56

标签: javascript node.js http request http-headers

我想用节点js模拟登录。该请求是发布请求,并返回302。

当我想用节点中的请求模拟它时,出现错误:

Unhandled rejection StatusCodeError: 302 

但是当我查看google chrome时,响应为空,但是有Cookie响应。如何通过节点请求获取此Cookie?

enter image description here

1 个答案:

答案 0 :(得分:1)

Here is sample code for getting cookies:

$.ajax({
    type: "POST",
    url: AppConstants.URLs.PROXY,
    data: message,
    xhrFields: {
        withCredentials: true
    },
    success: function(data, status, xhr) {
        console.log("Cookie: " + xhr.getResponseHeader("Set-Cookie"));
    }
});

You can set cookies from server side at node.js using Cookies-js

How can i get this cookie with a node request?

var jsdom = require('jsdom');
var window = jsdom.jsdom().parentWindow;
var Cookies = require('cookies-js')(window);

// First set a cookie
Cookies.set('key', 'value');

// Get the cookie value
Cookies.get('key'); // "value"

// Using the alias
Cookies('key'); // "value"

Hope this helps.