test-headers.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. try {
  2. require('tough-cookie')
  3. } catch (e) {
  4. console.error('tough-cookie must be installed to run this test.')
  5. console.error('skipping this test. please install tough-cookie and run again if you need to test this feature.')
  6. process.exit(0)
  7. }
  8. var server = require('./server')
  9. , assert = require('assert')
  10. , request = require('../index')
  11. , s = server.createServer()
  12. s.listen(s.port, function () {
  13. var serverUri = 'http://localhost:' + s.port
  14. , numTests = 0
  15. , numOutstandingTests = 0
  16. function createTest(requestObj, serverAssertFn) {
  17. var testNumber = numTests;
  18. numTests += 1;
  19. numOutstandingTests += 1;
  20. s.on('/' + testNumber, function (req, res) {
  21. serverAssertFn(req, res);
  22. res.writeHead(200);
  23. res.end();
  24. });
  25. requestObj.url = serverUri + '/' + testNumber
  26. request(requestObj, function (err, res, body) {
  27. assert.ok(!err)
  28. assert.equal(res.statusCode, 200)
  29. numOutstandingTests -= 1
  30. if (numOutstandingTests === 0) {
  31. console.log(numTests + ' tests passed.')
  32. s.close()
  33. }
  34. })
  35. }
  36. // Issue #125: headers.cookie shouldn't be replaced when a cookie jar isn't specified
  37. createTest({headers: {cookie: 'foo=bar'}}, function (req, res) {
  38. assert.ok(req.headers.cookie)
  39. assert.equal(req.headers.cookie, 'foo=bar')
  40. })
  41. // Issue #125: headers.cookie + cookie jar
  42. //using new cookie module
  43. var jar = request.jar()
  44. jar.setCookie('quux=baz', serverUri);
  45. createTest({jar: jar, headers: {cookie: 'foo=bar'}}, function (req, res) {
  46. assert.ok(req.headers.cookie)
  47. assert.equal(req.headers.cookie, 'foo=bar; quux=baz')
  48. })
  49. // Issue #794 add ability to ignore cookie parsing and domain errors
  50. var jar2 = request.jar()
  51. jar2.setCookie('quux=baz; Domain=foo.bar.com', serverUri, {ignoreError: true});
  52. createTest({jar: jar2, headers: {cookie: 'foo=bar'}}, function (req, res) {
  53. assert.ok(req.headers.cookie)
  54. assert.equal(req.headers.cookie, 'foo=bar')
  55. })
  56. // Issue #784: override content-type when json is used
  57. // https://github.com/mikeal/request/issues/784
  58. createTest({
  59. json: true,
  60. method: 'POST',
  61. headers: {'content-type': 'application/json; charset=UTF-8'},
  62. body: {hello: 'my friend'}},function(req, res) {
  63. assert.ok(req.headers['content-type']);
  64. assert.equal(req.headers['content-type'], 'application/json; charset=UTF-8');
  65. }
  66. )
  67. // There should be no cookie header when neither headers.cookie nor a cookie jar is specified
  68. createTest({}, function (req, res) {
  69. assert.ok(!req.headers.cookie)
  70. })
  71. })