我需要开发一个 JavaScript 移动应用程序,需要将身份验证 token 发布到 Microsoft 网站。
我在网上找到了大部分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 无效。
最佳答案
Can somebody highlight the differences in these two posts?
这两个“POST”之间的主要区别在于,javascript 是在具有跨源限制的浏览器中完成的,而 php“POST”是在没有此类限制的服务器上完成的。
And can somebody build a javascript post just like the php one?
如果目标服务器启用了 CORS,那么您所拥有的看起来不错
如果目标服务器未启用 CORS,则不,不直接
关于javascript - Ajax POST 无法正常工作,PHP 对应的工作完美,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31892803/