Javascript AJAX使用GET而不是POST
我有一个运行jQuery的非常简单的HTML页面,它正试图发布到RESTAPI。这是我的密码Javascript AJAX使用GET而不是POST,javascript,jquery,ajax,rest,Javascript,Jquery,Ajax,Rest,我有一个运行jQuery的非常简单的HTML页面,它正试图发布到RESTAPI。这是我的密码 <script type="text/javascript" language="javascript"> var user = 'someuser'; var pass = 'somepassword'; var payload = { "value1": "first value", "value2": "second value"
<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>
以下是原始请求,在Fiddler中捕获:
还有原始的反应,也在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."}
它是作为GET请求发送的,因为JSONP使用指向web服务(执行GET请求)的
src
属性将脚本附加到您的网页上,然后返回脚本,其中包含所有绑定在回调函数中的请求数据
显然,如果您愿意使用iframe等进行一些重要的腿部工作,那么可以通过JSONP执行POST请求(请参阅),但对于大多数意图和目的,您只能获得请求
从未设置授权标头,因为当前无法修改为添加到页面的脚本而发送的标头。此api是否返回jsonp?你为什么不加[回调)。你能分享screen,network->xhr吗?如果我将数据类型从
JSONP
更改为JSON
,问题将变成一个选项请求。JSONP是一个GET请求,这就是JSONP的工作方式。如果我删除JSONP
,生成的请求将变成一个OPTIONS
请求。@amber我相信这是因为你设置了g自定义标题。看到了吗?我注释掉了发送前处理程序,实际上得到了一个POST
,但服务器返回了一个未授权的401。查看原始请求,我没有看到任何与用户
和密码
设置值设置的授权信息。我相信用户
字段应该是username
,您可能需要添加xhrFields:{withCredentials:true}
也是,但我不太确定。查找$的设置。Ajax
,您是正确的,它应该是用户名
,所以这是固定的。我添加了您建议的xhrField。我仍然没有在请求中看到授权标头。
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"}
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."}