如何在Angular 4中使用HttpInterceptor设置头x-api-key

时间:2017-10-25 14:01:18

标签: javascript angular

我尝试使用HttpInterceptor设置标头键和值,但是我收到此错误:

  

无法加载   https://example.com/api/agency:   对预检请求的响应没有通过访问控制检查:否   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:4200'因此是不允许的   访问。响应的HTTP状态代码为403。

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('x-api-key', 'MY_TOKEN_VALUE')});
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
  }
}

标题键为x-api-key

1 个答案:

答案 0 :(得分:0)

API托管在亚马逊AWS上,因此我必须设置代理来修复问题。