如何使用POST或GET发送带有有效负载的PUT请求?

问题描述 投票:0回答:2

我需要将带有有效负载的PUT请求发送到API(Philips Hue Bridge),但是我在javascript中有一些限制。我可以[[only使用:

XMLHttpRequest方法:

open(method, url [, async = true [, username = null [, password = null]]])

设置请求方法,请求URL和同步标志。支持的请求方法:GET,POST

send(data = null)

发起请求。可选的“数据”参数仅允许使用UTF-8编码的字符串类型。如果请求方法是GET,则忽略该参数。

abort()

取消任何网络活动。

Philips Hue Bridge API期望:

URL:

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

方法:

PUT

有效负载示例:

{"on": true}我尝试过的事情:

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

响应:

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

响应:

400 (Bad request)也尝试了GETPOST,并带有以下URL结尾:../state?{on=true}../state?{on:true}../state?{"on"=true}../state?{"on":true}

响应:

400 (Bad request)同样,除了上面提到的XMLHttpRequest方法之外,我不能使用任何其他库或命令。

我该如何解决?

javascript philips-hue
2个回答
1
投票
下面是示例代码。您可以在代码中尝试这种方式。

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);


0
投票
method属性更改为PUT应该可以解决问题。

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

© www.soinside.com 2019 - 2024. All rights reserved.