Angular2 XHRFields withCredentials为true

5

我是一个系统的用户,正在尝试登录。在Angular 1中,有方法可以设置

withCredentials:true

但是我在Angular 2中找不到可行的解决方案。

export class LoginComponent {
    constructor(public _router: Router, public http: Http, ) {

    }


    onSubmit(event,username,password) {
        this.creds = {'Email': 'harikrishna@gmail.com','Password': '01010','RememberMe': true}
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');

        this.http.post('http://xyz/api/Users/Login', {}, this.creds)
              .subscribe(res => {
                  console.log(res.json().results);

              });
     }

}
7个回答

8
在Angular >2.0.0中(实际上是从RC2开始),只需
http.get('http://my.domain.com/request', { withCredentials: true })

我花了很长时间寻找这个...谢谢。 - ARM
同样,我花了很多时间试图解决这个问题。我的一个问题是,我不知道问题出在哪里(或者至少需要一段时间才能追踪到)。 我看到的是,我得到了一个 401 响应,而请求似乎是完美的。 - Chris Gilbert

5
据我所知,目前(beta.1版本)该选项不可用。您需要使用类似以下内容的方法解决:
```javascript // your code here ```
let _build = http._backend._browserXHR.build;

http._backend._browserXHR.build = () => {
  let _xhr =  _build();
  _xhr.withCredentials = true;
  return _xhr;
};

这在Chrome和Firefox中可行,但在Safari中失败了。有什么想法? - harikrish
不仅仅是针对这个问题,但目前的beta版本(beta.7)在Safari浏览器上仍存在一些问题(例如国际化API)。 - cexbrayat
你能告诉我你发送API时使用了哪些头信息吗? 这是我发送的内容 headers = { headers: new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json'
}) };
- harikrish
我已经创建了一个 login.service.ts 文件用于登录 (ionic 2),请问我应该把这段代码放在哪里才能让它起作用? - Brampage
这对我非常有效,谢谢!你用它构建了单元测试吗?我在模拟这部分时遇到了麻烦。http://stackoverflow.com/questions/37806956/unit-tests-using-withcredentials-flag - Aarmora
@cexbrayat 在哪里以及如何注入它?如何使用上述方法进行任何HTTP请求? - UzUmAkI_NaRuTo

2

Angular2团队已经注意到了这个问题。

你可以在问题链接中找到其他解决方法(其中一个特别是作为@Injectable编写的)。


链接无效。 - Playdome.io
这是有效的...好吧,这就是链接的生命周期 :( - grebett
我在某处读到过这样的说法,随意在答案中发布链接并不是一个好主意,因为它们可能会随着时间的推移而消失。链接是好的,但至少应该复制粘贴其含义内容 :) - Playdome.io

1

如果有人使用纯JS,基于cexbrayat的答案:

app.Service = ng.core
    .Class({
        constructor: [ng.http.Http, function(Http) {
            this.http = Http;
            var _build = this.http._backend._browserXHR.build;
            this.http._backend._browserXHR.build = function() {
                var _xhr = _build();
                _xhr.withCredentials = true;
                return _xhr;
            };
        }],

0

我认为您没有正确使用post方法。您可以尝试类似于这样的做法:

onSubmit(event,username,password) {
  this.creds = {
    'Email': 'harikrishna@gmail.com',
    'Password': '01010','RememberMe': true
  }

  this.headers = new Headers();
  this.headers.append('Content-Type', 'application/json');

  this.http.post('http://xyz/api/Users/Login', 
                 JSON.stringify(this.creds),
                 { headers: headers });
}

您倒置了参数。第二个参数对应发送到POST中的内容,应定义为字符串。对象在此级别上尚不受支持。请参阅此问题: https://github.com/angular/angular/issues/6538

如果您想设置特定标题,则需要在post方法的第三个参数中添加Headers对象。

否则,我认为withCredentials属性与CORS有关,如果您想要在跨域请求中发送cookie,则可以查看此链接以获取更多详细信息:

希望这些对您有所帮助, Thierry


0

针对带有 withCredentials : yes 的CORS问题,我将认证令牌作为参数发送。

req = req.clone({
    //withCredentials: true,
    setHeaders: { token: _token },
    setParams: {
         token: _token,
     }
});

0
getHeaders(): RequestOptions {
    let optionsArgs: RequestOptionsArgs = { withCredentials: true }
    let options = new RequestOptions(optionsArgs)
    return options;
  }

getAPIData(apiName): Observable<any> {`enter code here`
    console.log(Constants.API_URL + apiName);
    let headers = this.getHeaders();
    return this.http
      .get(Constants.API_URL + apiName, headers)
      .map((res: Response) => res.json())
  }

1

在 WebAPI 中启用了 CORS

2

同样的代码在Chrome(正常模式)、Internet Explorer中运行良好。

但在隐身模式下的Chrome、Firefox和Edge中,它会要求Windows登录提示。

请分享如何解决此问题的建议。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接