如何在https请求中将会话或cookie设置为url?

时间:2019-04-03 11:35:28

标签: javascript node.js

我正在使用 Node.js 在URL下通过get https请求进行调用,这里我需要发送带有cookie的会话,因为我知道cookie的种类。

var URL = require('url-parse');

var appurl = "https://test.somedomain.com"
var https = require('https');
var url = new URL(appurl);
var options = {
    host: url.host,
    url: appurl,
    path: url.pathname + url.query,
    method: 'GET',
    headers: {
        "Set-Cookie": "cookiValue1=abcdesg"
    }
};

var req = https.request(options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    // console.log(res.headers.)
    // res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ', chunk);
    });
});
req.on('error', function (e) {
    console.log('problem with request: ' + e.message);
});

req.write('data\n');
req.write('data\n');
req.end();

2 个答案:

答案 0 :(得分:0)

标题应该是Cookie而不是Set-Cookie

服务器使用

Set-Cookie在客户端上设置cookie。标题Cookie用于由客户端向服务器发送cookie。

答案 1 :(得分:0)

nodejs服务器不是具有windowdocument

的浏览器

尝试在js客户端而不是nodejs中发送相同的请求

您只能在此处设置cookie

请参阅底部的指针

var URL = require('url-parse');
var https = require('https');
var appurl = "https://stackoverflow.com/"
var url = new URL(appurl);
var options = {
    host: url.host,
    url: appurl,
    path: url.pathname + url.query,
    method: 'GET',
    headers: {
        "Cookie": "1111111111=abcdesg", // POINTER its unfortunately useless
        "Set-Cookie": "11111111=abcdesg" // POINTER its unfortunately useless
    }
};

var req = https.request(options, function (res) {
    console.log('before HEADERS: ' + JSON.stringify(res.headers));
    res.headers.cookiValue1 = 'abcdesg'; // POINTER
    console.log('after HEADERS: ' + JSON.stringify(res.headers));

});
req.on('error', function (e) {
    console.log('problem with request: ' + e.message);
});

req.write('data\n');
req.write('data\n');
req.end();