0

I'm trying to implement an access to my Nest account using javascript (in same way it done before/and it is working) in android native app (java), we successfully access the nest account in as following:

final String BASE_URL =
        "https://home.nest.com/user/login?";
final String USERNAME_PARAM = "username";
final String PASSWORD_PARAM = "password";

Uri builtUri = Uri.parse(BASE_URL).buildUpon()
        .appendQueryParameter(USERNAME_PARAM, mEmail)
        .appendQueryParameter(PASSWORD_PARAM, mPassword)
        .build();

URL url = new URL(builtUri.toString());

// Create the request, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("http.agent", "Nest/1.1.0.10 CFNetwork/548.0.4");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.connect();

// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();

But when I try to do the same in Javascript, I get the following error:

XMLHttpRequest cannot load https://home.nest.com/user/login?username=myemail@domain.com&password=XXXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'domain.com' is therefore not allowed access. The response had HTTP status code 401.

My Javascript:

var BASE_URL = "https://home.nest.com/user/login?";
var USERNAME_PARAM = "username";
var PASSWORD_PARAM = "password";

var url = BASE_URL +  USERNAME_PARAM + "=" + mEmail
    + "&" + PASSWORD_PARAM + "=" + mPassword; // pass in a URI as a string and parse that 


$.ajax({
    headers: { "http.agent": "Nest/1.1.0.10 CFNetwork/548.0.4" },
    type: "POST",
    url: url,
    contentType: "application/x-www-form-urlencoded",
    dataType: "json",
    success: function (response) {
        console.log("Success:" + JSON.stringify(response));           
    },
    error: function (response) {
        console.error("Error:" + JSON.stringify(response));
    }
});

Any idea what is the problem?, why it works in java, I also tried using the Postman - REST Client extension, and it works perfect!!!

Thanks, Joseph

Joseph
  • 1,716
  • 3
  • 24
  • 42

1 Answers1

0

CORS. look at the yellow portion of your question... your request doesn't pass the cross site scripting check which means you cannot do this call using AJAX, can you use JSONP? Btw, JSONP can be used by GET only.

The solution for this is to implement a proxy if you need.

Yuki
  • 742
  • 7
  • 11