test-request-methods.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var sys = require("util")
  2. , assert = require("assert")
  3. , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
  4. , http = require("http")
  5. , xhr;
  6. // Test server
  7. var server = http.createServer(function (req, res) {
  8. // Check request method and URL
  9. assert.equal(methods[curMethod], req.method);
  10. assert.equal("/" + methods[curMethod], req.url);
  11. var body = (req.method != "HEAD" ? "Hello World" : "");
  12. res.writeHead(200, {
  13. "Content-Type": "text/plain",
  14. "Content-Length": Buffer.byteLength(body)
  15. });
  16. // HEAD has no body
  17. if (req.method != "HEAD") {
  18. res.write(body);
  19. }
  20. res.end();
  21. if (curMethod == methods.length - 1) {
  22. this.close();
  23. console.log("done");
  24. }
  25. }).listen(8000);
  26. // Test standard methods
  27. var methods = ["GET", "POST", "HEAD", "PUT", "DELETE"];
  28. var curMethod = 0;
  29. function start(method) {
  30. // Reset each time
  31. xhr = new XMLHttpRequest();
  32. xhr.onreadystatechange = function() {
  33. if (this.readyState == 4) {
  34. if (method == "HEAD") {
  35. assert.equal("", this.responseText);
  36. } else {
  37. assert.equal("Hello World", this.responseText);
  38. }
  39. curMethod++;
  40. if (curMethod < methods.length) {
  41. console.log("Testing " + methods[curMethod]);
  42. start(methods[curMethod]);
  43. }
  44. }
  45. };
  46. var url = "http://localhost:8000/" + method;
  47. xhr.open(method, url);
  48. xhr.send();
  49. }
  50. console.log("Testing " + methods[curMethod]);
  51. start(methods[curMethod]);