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

后端 未结 3 981
无人及你
无人及你 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:26

    This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


    Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

    // NB:- node's http client API has changed since this was written
    // this code is for 0.4.x
    // for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request
    
    var http = require('http');
    
    var data = JSON.stringify({ 'important': 'data' });
    var cookie = 'something=anything'
    
    var client = http.createClient(80, 'www.example.com');
    
    var headers = {
        'Host': 'www.example.com',
        'Cookie': cookie,
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data,'utf8')
    };
    
    var request = client.request('POST', '/', headers);
    
    // listening to the response is optional, I suppose
    request.on('response', function(response) {
      response.on('data', function(chunk) {
        // do what you do
      });
      response.on('end', function() {
        // do what you do
      });
    });
    // you'd also want to listen for errors in production
    
    request.write(data);
    
    request.end();
    

    What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

提交回复
热议问题