【发布时间】:2016-12-25 22:24:33
【问题描述】:
我有一个非常简单的运行 jQuery 的 HTML 页面,它试图发布到 REST API。这是我的代码。
<script type="text/javascript" language="javascript">
var user = 'someuser';
var pass = 'somepassword';
var payload = {
"value1": "first value",
"value2": "second value"
};
var rootUrl = 'http://someinternalserver:8888/api/Method';
</script>
<script language="javascript" type="text/javascript" id="postWtnBlock">
function postValue_Go() {
$.ajax({
url: rootUrl,
// Removing the next line or changing the value to 'JSON' results in an OPTIONS request.
dataType: 'JSONP',
data: JSON.stringify(payload),
method: 'POST',
user: user,
password: pass,
beforeSend: function (req) {
req.setRequestHeader('Authorization', 'BASIC ' + btoa(user + ':' + pass));
},
success: function (data) {
alert(data);
},
error: function (xhr) {
alert(xhr.status + ' ' + xhr.statusText);
}
});
}
</script>
这里发生了两件事。
1) 每个请求都作为 GET 请求发送,而不是 POST。 2) Authorization Header 永远不会进入请求;它总是丢失。
我不知道这是为什么。
更新 #1: 新的 postValue_Go() 看起来像这样...
function postValue_Go() {
$.ajax({
url: rootUrl,
data: JSON.stringify(payload),
method: 'POST',
username: user,
password: pass,
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
},
error: function (xhr) {
alert(xhr.status + ' ' + xhr.statusText);
}
});
}
这是 Fiddler 中捕获的原始请求:
POST http://someinternalserver:8888/api/Method/ HTTP/1.1
Host: someinternalserver:8888
Connection: keep-alive
Content-Length: 693
Accept: */*
Origin: http://devserver
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://devserver/samples/ExternalAPI/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: someCookieValue=Boo; someOtherCookieValue=Yum;
{"value1": "first value","value2": "second value"}
还有原始响应,也可以在 Fiddler 中捕获。
HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 19 Aug 2016 17:12:29 GMT
Content-Length: 61
{"Message":"Authorization has been denied for this request."}
【问题讨论】:
-
这个api返回jsonp吗?以及为什么不添加 [stackoverflow.com/questions/7613815/… 回调)。你能分享屏幕,网络->xhr 吗?
-
如果我将数据类型从
JSONP更改为JSON,问题就变成了一个 OPTIONS 请求。 -
JSONP 是一个 GET 请求,这就是 JSONP 的工作原理。
标签: javascript jquery ajax rest