加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – $httpProvider.defaults.withCredentials的Angular

发布时间:2020-12-17 18:08:57 所属栏目:安全 来源:网络整理
导读:我有与 this问题完全相同的问题,但对于Angular 2. 总而言之,当向另一个域发送HTTP请求时,即使正确设置了CORS头,也不会发送JSESSIONID cookie. Angular 1.x解决方案是设置以下配置: .config(function ($routeProvider,$httpProvider) { $httpProvider.defaul
我有与 this问题完全相同的问题,但对于Angular 2.

总而言之,当向另一个域发送HTTP请求时,即使正确设置了CORS头,也不会发送JSESSIONID cookie.
Angular 1.x解决方案是设置以下配置:

.config(function ($routeProvider,$httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    //rest of route code

但是我找不到Angular 2的任何替代解决方案.

任何的想法?谢谢!

解决方法

您需要扩展默认的Http服务并将withCredentials设置为true

http.service.ts

import { Injectable } from '@angular/core';
import { Headers,Http,Request,RequestOptions,Response,XHRBackend } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService extends Http {
  constructor(backend: XHRBackend,options: RequestOptions) {
    super(backend,options);
  }

  request(url: string | Request,options?: any): Observable<Response> {
    if (typeof url === 'string') {
        if (!options) {
            options = {headers: new Headers()};
        }
        options.withCredentials = true;
    } else {
        url.withCredentials = true;
    }

    return super.request(url,options);
  }
}

http.service.factory.ts

import { RequestOptions,XHRBackend } from '@angular/http';
import { HttpService } from './http.service';

export function HttpServiceFactory(backend: XHRBackend,defaultOptions: RequestOptions) {
  return new HttpService(backend,defaultOptions);
};

在您的模块文件中,您需要替换您的http服务

import { HttpServiceFactory } from './http.service.factory';
import { Http,XHRBackend } from '@angular/http';

...

providers: [
  {
    provide: Http,useFactory: HttpServiceFactory,deps: [XHRBackend,RequestOptions]
  }
]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读