【问题标题】:angular 2 http withCredentialsangular 2 http withCredentials
【发布时间】:2016-12-01 14:19:13
【问题描述】:

我正在尝试使用 withCredentials 将 cookie 发送到我的服务,但不知道如何实现它。 文档说“如果服务器需要用户凭据,我们将在请求标头中启用它们”,没有示例。 我尝试了几种不同的方法,但它仍然不会发送我的 cookie。 到目前为止,这是我的代码。

private systemConnect(token) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('X-CSRF-Token', token.token);
    let options = new RequestOptions({ headers: headers });
    this.http.post(this.connectUrl, { withCredentials: true }, options).map(res => res.json())
    .subscribe(uid => {
        console.log(uid);
    });
}

【问题讨论】:

    标签: angular angular2-services angular2-http


    【解决方案1】:

    尝试像这样更改您的代码

    let options = new RequestOptions({ headers: headers, withCredentials: true });
    

    this.http.post(this.connectUrl, <stringified_data> , options)...
    

    如您所见,第二个参数应该是要发送的数据(使用JSON.stringify 或仅使用'')以及第三个参数中的所有选项。

    【讨论】:

    • 它已经在用于 Headers 和 RequestOptions 源文件的 cmets 中)直到官方 API 文档尚未准备好 - 我们必须在源代码中使用 cmets)
    • 由于 HttpClient 是标准,现在已经过时了
    • HttpClient 的正确解决方案在这里:stackoverflow.com/questions/47304912/…
    【解决方案2】:

    从 Angular 4.3 开始,HttpClient and Interceptors were introduced.

    一个简单的例子如下所示:

    @Injectable()
    export class WithCredentialsInterceptor implements HttpInterceptor {
    
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
            request = request.clone({
                withCredentials: true
            });
    
            return next.handle(request);
        }
    }
    
    constructor(
          private http: HttpClient) {
    
    this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
        .subscribe(result => {
            this.forecasts = result;
        },
        error => {
            console.error(error);
        });
    

    记得为您的应用模块提供拦截器,正如article 所说:

    为了为我们的应用程序激活拦截器,我们需要将它提供给 app.module.ts 文件中的主应用程序模块 AppModule:

    您的@NgModule 需要将其包含在其提供程序中:

      ...
      providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: WithCredentialsInterceptor,
        multi: true
      }],
      ...
    

    【讨论】:

      【解决方案3】:

      创建一个Interceptor 将内容注入到整个应用程序的标头中是个好主意。另一方面,如果您正在寻找需要在每个请求级别上完成的快速解决方案,请尝试将withCredentials 设置为true,如下所示

      const requestOptions = {
       headers: new HttpHeaders({
        'Authorization': "my-request-token"
       }),
       withCredentials: true
      };
      

      【讨论】:

        猜你喜欢
        • 2016-10-07
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-03
        • 1970-01-01
        • 2018-01-21
        相关资源
        最近更新 更多