angular 2 个 http withCredentials

angular 2 http withCredentials

我正在尝试使用 withCredentials 将 cookie 发送到我的服务,但找不到如何实现它。 文档说 "If the server requires user credentials, we'll enable them in the request headers" 没有例子。 我尝试了几种不同的方法,但它仍然不会发送我的 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);
    });
}

尝试像这样更改您的代码

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

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

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

从 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所说:

In order to activate the interceptor for our application we need to provide it to the main application module AppModule in file app.module.ts:

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

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

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

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