请注意,请求是跨域的,并且启用了CORS。
有一件事是拙劣的:虽然内容类型是' application / json'并且是必需的,POST数据实际上不是JSON,而是更多的查询字符串,其值为JSON。 假设上述问题现在无法纠正(需要更改服务器端)。
以下是我提出的卷曲请求:
curl --verbose
-d 'input={"value": "On", "wait": true, "timeout": 5000}'
-H "Content-Type:application/json"
<url>
请求已成功完成,并提供以下详细信息:
* Hostname was NOT found in DNS cache
* Trying <IP>...
* Connected to <URL PORT etc>
> POST <URL> HTTP/1.1
> User-Agent: curl/7.36.0
> Host: <HOST:PORT>
> Accept: */*
> Content-Type:application/json
> Content-Length: 52
>
* upload completely sent off: 52 out of 52 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Date: Wed, 14 May 2014 12:05:14 GMT
< content-type: application/json
< Access-Control-Allow-Headers: content-type
< Access-Control-Allow-Origin: *
<
* Closing connection 0
{"name":"power","value":"On"}%
通过JavaScript XMLHttpRequest进行的相同请求不起作用。这是代码:
var querydata = "input={\"value\": \"On\", \"wait\": true, \"timeout\": 5000}";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if (xhr.status == 200) {
console.log('power on succeeded.');
} else {
console.log('error occurred:' + xhr.statusText);
console.log('error data:' + xhr.responseText);
}
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(querydata);
请求最终为400:BAD REQUEST,包含服务器的特定错误。
以下是请求 - 响应详细信息(来自Firefox检查器):
HTTP OPTIONS调用: 请求:
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0
Pragma: no-cache
Origin: null
Host: <HOST:PORT>
DNT: 1
Connection: keep-alive
Cache-Control: no-cache
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
响应:
Date: Wed, 14 May 2014 12:11:32 GMT
Content-Type: text/plain
Access-Control-Allow-Origin: *
access-control-allow-headers: content-type
HTTP POST调用: 请求:
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0
Pragma: no-cache
Origin: null
Host: <HOST:PORT>
DNT: 1
Content-Type: application/json; charset=UTF-8
Content-Length: 52
Connection: keep-alive
Cache-Control: no-cache
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
响应:
Date: Wed, 14 May 2014 12:11:32 GMT
Content-Type: text/plain
Access-Control-Allow-Origin: *
access-control-allow-headers: content-type
注意(虽然这可能听起来很愚蠢)我尝试了很多POST数据格式:
querydata = "input={\"value\": \"On\", \"wait\": true, \"timeout\": 5000}";
querydata = 'input={"value": "On", "wait": true, "timeout": 5000}';
querydata = "input={'value': 'On', 'wait': true, 'timeout': 5000}";
有人能指出我的错误吗?