views:

1139

answers:

3

The following function works in IE but not in Chrome:

function doStuff() {
  var request = new XMLHttpRequest();
  request.open("POST", "http://twitter.com/statuses/update.json", true, "USERNAME-HERE", "PASSWORD-HERE");
  request.send("status=STATUS UPDATE HERE");
}

Chrome generates the following request. Note the Authorization header is missing:

OPTIONS /statuses/update.json HTTP/1.1
Host: twitter.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.78 Safari/532.5
Access-Control-Request-Method: POST
Origin: file://
Access-Control-Request-Headers: Content-Type
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

I get the following response (http 401):

HTTP/1.1 401 Unauthorized
Date: Wed, 03 Feb 2010 00:39:33 GMT
Server: hi
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Twitter API"
X-Runtime: 0.00107
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache, max-age=300
Set-Cookie: _twitter_sess=BAh7BzoHaWQiJTUxMTc2Nzk4N2U0YzMzZmU0ZTQyNzI4NjQyYjI3ODE2Igpm%250AbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAG%250AOgpAdXNlZHsA--bb61324c3ba12c3cd1794b3895a906a69c154edd; domain=.twitter.com; path=/
Expires: Wed, 03 Feb 2010 00:44:33 GMT
Vary: Accept-Encoding
Content-Length: 73
Connection: close

{"request":"/statuses/update.json","error":"Could not authenticate you."}

So, how am I supposed to pass a username and password to XHR? Webkit/Safari documentation says the open method should take these parameters, so I'm not sure why it is failing.

A: 

Have you tried:

request.setRequestHeader('Authorization', 'yourvalue');
AJ
That won't really help him. Note that Chrome is sending an OPTIONS request.
EricLaw -MSFT-
@EricLaw he still needs to set Authorization header. And your answer is right too.
AJ
Adding Authorization doesn't help.
jeffamaphone
The authorization header will be automatically sent by the last two parameters of the Open() call. If the Open() call wasn't x-domain.
EricLaw -MSFT-
+3  A: 

From the look of it, you're trying to do an X-Domain XMLHTTPRequest, which is why Chrome sends the OPTIONS pre-flight request. Because the Twitter server doesn't respond to the OPTIONS request indicating that X-Domain access is okay, you get a failure here.

Your code would only work in IE in the Local Computer zone, or if you turn off x-domain-checking (very dangerous)

EricLaw -MSFT-
That is works in IE because of LMZ seems to be true.
jeffamaphone
+1  A: 

The solution was that I needed to add

request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

The way I'm doing this is... special... so this may not be of much use to others going forward. But once I added this webkit started adding Authorization.

jeffamaphone
glad request.setRequestHeader() was useful to you after all.
AJ