0

I need to send a PUT request with a payload to an API (Philips Hue Bridge), but I have some limitations in javascript. I can only use:

XMLHttpRequest methods:

open(method, url [, async = true [, username = null [, password = null]]])
Sets the request method, request URL, and synchronous flag. Supported request method : GET, POST

send(data = null)
Initiates the request. The optional 'data' argument allows only UTF-8 encoded string type. The argument is ignored if request method is GET.

abort()
Cancels any network activity.

This limitation comes from the Tizen Wearable Web Widget Specification


Philips Hue Bridge API expects:

URL: http://hostname/api/username/lights/lightKey/state

Method: PUT

Payload example: {"on": true}


What I tried:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
Response: 400 (Bad request)

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
Response: 400 (Bad request)

Also tried GET and POST with following URL endings:
../state?{on=true}
../state?{on:true}
../state?{"on"=true}
../state?{"on":true}
Response: 400 (Bad request)

Again, I cannot use any additional libraries or commands besides the XMLHttpRequest methods mentioned above.

How can I solve this?

  • Can you tell us what technologies/frameworks you're using? – Brant Jan 10 '20 at 14:51
  • Good point! Edited the question to include a pointer to "Tizen Wearable Web Widget Specification". – new_to_tizen Jan 10 '20 at 14:56
  • Based on their documentation - you can not do a PUT request. They've limited their implementation of XMLHttoRequest. You could create a server your self, POST from the app to the server, and then let the server do the PUT for you. – Brant Jan 10 '20 at 15:10
  • Ok, thank you. I thought there might be a way to emulate a PUT by using POST or GET, manipulating the URL or something... it's quite a bummer. I thought about a proxy server but it's not viable for the small app Im writing. – new_to_tizen Jan 11 '20 at 08:44

2 Answers2

1

below is the sample code. you can try this way in your code.

var http = new XMLHttpRequest();
var url = 'your_URL.php';
var params = 'on=true';
http.open('PUT', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);
Harsh Madaiyar
  • 166
  • 1
  • 4
0

Changing the method property to PUT should do the trick.

var xhr = new XMLHttpRequest();
xhr.open('PUT', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
Jesper
  • 3,816
  • 2
  • 16
  • 24