【发布时间】:2015-10-31 18:55:03
【问题描述】:
我需要开发一个需要将身份验证令牌发布到 Microsoft 网站的 javascript 移动应用。
我在网上找到了大部分的javascript代码,所以我尝试了一下,但失败了。
javascript 代码在控制台中返回“GET undefined/proxy/https://mysharepointonline.sharepoint.com/_forms/default.aspx?wa=wsignin1.0”消息。
我还发现了一个 WORKING PHP 版本的代码,对我来说,这似乎是在做同样的事情,但是 POST 的构建方式可能存在一些细微差别.
Javascript 代码在这里:
function getAuthCookies()
{
$.support.cors = true; // enable cross-domain query
$.ajax({
type: 'POST',
data: token, //this translates to the $token variable in php
crossDomain: true, // had no effect, see support.cors above
contentType: "application/json;odata=verbose", //'application/x-www-form-urlencoded',
headers: {
"Accept": "application/json;odata=verbose"
},
url: loginUrl, //this translates to the $url variable in php
// dataType: 'html', // default is OK: Intelligent Guess (xml, json, script, or html)
success: function (data, textStatus, result) {
//function to call when the POST was successfull.
refreshDigestViaREST();
},
error: function (result, textStatus, errorThrown) {
reportError(result, textStatus, errorThrown);
}
});
}
PHP 看起来像这样:
function getAuthCookies($token, $host) {
$url = $host . "/_forms/default.aspx?wa=wsignin1.0";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch,CURLOPT_VERBOSE, 1); // For testing
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
// catch error
if($result === false) {
throw new Exception('Curl error: ' . curl_error($ch));
}
//close connection
curl_close($ch);
return getCookieValue($result);
}
有人可以强调这两个帖子的区别吗? 有人可以像 php 一样构建一个 javascript 帖子吗?
编辑:
javascript 代码发出两个请求,一个接一个。第一个被临时移动,但它实际上在响应中有正确的数据。但是,第二个的 URL 无效。
【问题讨论】:
-
你应该显示 JavaScript
url变量是什么。 -
POST an authentication token to a Microsoft website.- 这个微软网站是否启用了 CORS? -
$.support.cors = true; // enable cross-domain query— 不是那样做的。这只是与 jQuery 的浏览器检测代码有关,因此如果 browser 不支持 CORS,那么它会让 jQuery 认为它支持并破坏它。不理会那个变量。 -
浏览器开发者工具中的控制台是怎么说的?网络标签说什么?你能看到请求吗?它的格式是否符合您的预期?反应如何?
-
昆汀:我可以看到请求。 “网络”选项卡中有 2 条消息。第一个格式正确,它的状态为 302(临时移动),并且这个在响应中有正确的 cookie。但是在这之后,有一个失败的请求,URL 不正确(undefined/proxy/https://mysharepoint.sharepoint.com
标签: javascript php jquery ajax post