How do I create a HTTP Client Request with a cookie?

后端 未结 3 983
无人及你
无人及你 2020-12-07 18:29

I\'ve got a node.js Connect server that checks the request\'s cookies. To test it within node, I need a way to write a client request and attach a cookie to it. I understa

3条回答
  •  忘掉有多难
    2020-12-07 19:29

    The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

    var options = { 
        hostname: 'example.com',
        path: '/somePath.php',
        method: 'GET',
        headers: {'Cookie': 'myCookie=myvalue'}
    };
    var results = ''; 
    var req = http.request(options, function(res) {
        res.on('data', function (chunk) {
            results = results + chunk;
            //TODO
        }); 
        res.on('end', function () {
            //TODO
        }); 
    });
    
    req.on('error', function(e) {
            //TODO
    });
    
    req.end();
    

提交回复
热议问题