添加授权标头时,Angular HttpInterceptor提示400错误的请求

时间:2018-11-30 02:44:01

标签: angular rest angular-http-interceptors bad-request

在尝试使用HTTPInterceptor添加授权标头时,我一直遇到HTTP错误-400(错误请求)

我与Postman进行了测试,并且可以正常工作 Tested with Postman

代码如下:

拦截器

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

@Injectable({
  providedIn: 'root'
})
export class InterceptrorService implements HttpInterceptor {

  constructor() {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    req = req.clone({
      setHeaders: {
    'x-api-key': 'a404823a-55b8-419e-bcbf-8ebb9ff7bae3',
    }
  });
  return next.handle(req);
 }

}

TestService

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TestService {

  constructor(private http: HttpClient) {
  }

  test() {
    return this.http.get('http://motorway:8000/wluntest/test');
  }
}

应用模块

providers: [
{
  provide: HTTP_INTERCEPTORS,
  useClass: InterceptrorService,
  multi: true
}

],

应用组件

constructor(private test: TestService) {
  this.test.test().subscribe(value => console.log(value));
}

400 - bad request

api是用Gravitee构建的模拟api

角度版本

Angular CLI: 6.2.4
Node: 10.13.0
OS: linux x64
Angular: 6.1.9
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Http Interceptor log

请帮助,谢谢

3 个答案:

答案 0 :(得分:1)

尝试添加这样的标题。

:h function-range-example

答案 1 :(得分:1)

您的问题是,响应主体不是JSON对象,因为http客户端将所有内容包装到Object(默认情况下)。所以你可以做什么:

  • 将响应主体更改为返回{ msg: 'hello' },然后在回调中通过console.log(value.msg)拾取它
  • 或在您的示例中通过添加{responseType: 'text'}来处理其事实,即纯文本:

    test() {
      return this.http.get('http://motorway:8000/wluntest/test', {responseType: 'text'});
    }
    

答案 2 :(得分:0)

这是由于后端(Gravitee)中的CROS而发生的 Access-Control-Allow-Headers需要配置为允许自定义标头。

有关:https://docs.gravitee.io/apim_publisherguide_configuring_cors.html

的更多信息