登录到一个网站,使用jQuery和JSON

Logon to a website and the use of jQuery and JSON

本文关键字:使用 jQuery JSON 网站 一个 登录      更新时间:2023-09-26

我有一个信息屏幕解决方案,其中计算机有一个本地存储的HTML页面,该页面将外部模板(包括功能Javascript等)加载到浏览器中。

此页面是本地的原因是,如果计算机在没有网络连接的情况下启动,或者服务器关闭,它将在一段时间内重试。

然而,有时这台计算机需要登录,所以我传递登录凭据并返回一个cookie。

<script type="application/javascript">
    url = "http://192.168.1.27:9000/carousel/1/template?user=test&password=test";
    function loadTemplate() {
        $( "#error" ).html("Loading...");
        $( "#message" ).html("");
        $('body').load(url, function( response, status, xhr ) {
            if ( status == "error" ) {
                $( "#error" ).html("<h3>Sorry but there was an error:<br/></font></h3>" + " Description: " + xhr.statusText + " (" + xhr.status + ")");
            }
        });
    }
</script>

然而,在随后的请求(作为模板加载的一部分)中,这个cookie似乎不会被传递。

我尝试使用:

加载
$.ajax("${dataUrl.raw()}",
{
    xhrFields: {
        withCredentials: true
    }, crossDomain: true
}).done(function(data) {
});

但是他的结果是以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.27:9000/carousel/1/data.json. (Reason: CORS header 'Access-Control-Allow-Origin' does not match '*').

在没有xhrFields的情况下加载它可以加载,但是用户没有登录,这表明cookie没有在请求中传递。我可以选择在每个数据请求中包含登录凭据,但我更喜欢在启动时只做一次,并使用具有较长生命周期的cookie。

(编辑:)

我试图为'Access-Control-Allow-Origin'添加不同的值,但传入'file://',这似乎是在本地文件系统调用的情况下的起源不工作,因为据说不匹配,或者chromium说t'null'是不允许的(从技术上讲,我认为这是因为我在'file://'之后什么也没有)

在CORS请求中,服务器(http://192.168.1.27:9000)需要允许使用发送cookie,否则将抛出错误。要启用此功能,服务器需要使用以下头

进行响应
Access-Control-Allow-Credentials: true

你可以在这里阅读更多关于这个标题:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Credentials

另外,你能从localhost提供这个页面吗?我不确定file://是如何与CORS头一起玩的。

同时,确保你的服务器正在传递这个header

Access-Control-Allow-Origin: *

*将允许任何网站,但你可以把它的范围,只是一个单一的域。