ma11hew28
ma11hew28

Reputation: 126507

Server-Side JavaScript: HTTP GET with cookie?

I have a UI Automation script, written in JavaScript. From that script, how do I execute a GET request to a URL with a cookie? E.g:

curl "https://example.com/path?a=123&b=cool" --cookie "c=12"

Or, if you know how to run system commands from JavaScript, like you can do in Ruby, that'll work too.

Upvotes: 0

Views: 1028

Answers (2)

ma11hew28
ma11hew28

Reputation: 126507

After checking out HTTP GET request in JavaScript? and reading step 7 of "3.6.2. The setRequestHeader() method" in the W3C specs for XMLHttpRequest, I came up with:

function httpGet(url, opts={}) {
  var client = new XMLHttpRequest();
  client.open('GET', url, false); // not async
  if (opts.cookie) {
    client.setRequestHeader('Cookie', opts.cookie);
  }
  client.send();
}

FYI, I'm disregarding the response because I'm deleting a resource (perhaps I should verify the correct response so that I know the resource was deleted). So, yes, this should be a DELETE request, but they configured the server to accept a GET request, and I have no control over this.

Upvotes: 1

hross
hross

Reputation: 3671

See this thread on using jQuery to set cookies in the browser.

Upvotes: 1

Related Questions