简体   繁体   中英

How to set the session or cookie in https request to url?

I am calling below url with get https request using Node.js , here i need to send the session with cookie, since i know the vallue of 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();

The header should be Cookie instead of Set-Cookie

Set-Cookie is used by the server to set a cookie on clients. Header Cookie is used to send a cookie to server by client.

So nodejs server it's not a browser which have window and document

try to send the same request in js client side not nodejs

You can set cookie only here

see POINTERs in the bottom

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM