【问题标题】:angular 5 get cookies with domainangular 5 获取带有域的 cookie
【发布时间】:2019-04-07 19:58:31
【问题描述】:

(离子 3)

我正在对页面进行身份验证以访问一些 js 文件。

要访问我需要登录的文件,登录后我可以访问在请求进入后加载的这些库:

192.168.0.102:8080/web/backend

我提出了一个要求。

this.http.post ("/ auth", params, {headers: headers, withCredentials: true});

请求成功,但无法访问库,出现错误“404 not found”

这是因为当我发出 ajax 请求时,我有一个带角度的代理能够发出请求

{
   "path": "/auth"
   "proxyUrl": "192.168.0.102:8080/web/authenticate"
}

请求返回一个 cookie,这就是问题所在,cookie 返回一个域“localhost”,当尝试加载文件时,我无法执行以下测试。

1- 使用 firefox 登录,然后刷新 Angular 服务器以查看它们是否加载: 该页面可以加载文件,因为我有一个域为“192.168.0.102”的 cookie。

2- 删除 cookie 并返回使用 angular 登录,我安装了一个名为 cookieManager 的 firefox 扩展并编辑 cookie 以使 url 不是 localhost: 通过更改 cookie(域)的 url,我可以加载 js 文件。

问题出在哪里? 我必须更改从主机恢复的 cookie 的域并放置服务器的域才能使用该 cookie。

【问题讨论】:

    标签: angular ionic-framework cookies ionic3


    【解决方案1】:

    当我使用 this.http.post(...) 时,使用 Cookie 对我来说从来没有用过。而是使用XMLHttpRequest:

    let data = {
            email: this.loginField,
            password: this.passwordField
          }
    
      var xhr = new XMLHttpRequest();
      xhr.open("POST","http://localhost:8080/login", true);
      xhr.withCredentials = true;
    
      var change = () => {
        if(xhr.readyState == XMLHttpRequest.DONE) {
    
          //Return 401 Error code in your Backend (JSON Format)
          if (xhr.status != 401) {
    
            //User is allowed to log in
            this.navCtrl.setRoot(HomePage);
            localStorage.setItem("user", xhr.responseText);
    
          } else {
            //User isnt allowed to log in -> Error Handling
            console.log("Wrong Email or password");
            this.incorrectInupt();
          }
        }
      }
    
      xhr.onreadystatechange = change;
    
      xhr.setRequestHeader("Access-Control-Allow-Origin","http://localhost:8100");
      xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
      xhr.setRequestHeader("Content-Type", "application/json");
    
      xhr.send(JSON.stringify(data));
    

    现在 cookie 已安装在 Ionic-Client 中。

    注意:如果您的 Ionic-Server 也在 localhost:8100 上运行,您只需复制粘贴请求标头即可。否则,将请求标头中的链接更改为您的 Ionic-Server-Adress。

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 2020-02-20
      • 2019-03-21
      • 2018-07-08
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多