54

我正在尝试使用 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);
    });
}
4

3 回答 3

63

尝试像这样更改您的代码

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

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

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

于 2016-07-27T14:21:30.553 回答
25

从 Angular 4.3 开始,引入了 HttpClient 和拦截器。

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

@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);
    });

请记住为您的应用程序模块提供拦截器,如文章所述

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

@NgModule需要将其包含在其提供者中:

  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: WithCredentialsInterceptor,
    multi: true
  }],
  ...
于 2018-04-10T15:48:54.407 回答
8

Creating an Interceptor would be good idea to inject stuff into header across the application. On the other hand, if you are looking for a quick solution that needs to be done on a per request level, try setting withCredentials to true as below

const requestOptions = {
 headers: new HttpHeaders({
  'Authorization': "my-request-token"
 }),
 withCredentials: true
};
于 2018-11-25T21:19:01.567 回答