Angular 4 - Http request error: You provided 'undefined' where a stream was expected

前端 未结 2 869
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 05:19

While trying to do a HTTP Post request I am receiving the following error:

auth.service.ts?c694:156 Something went wrong requesting a new password, erro

2条回答
  •  佛祖请我去吃肉
    2021-02-14 05:52

    After a lot a lot of effort, I have managed to locate and fix the problem. The problem was that I have an authorization interceptor that is intercepting every request to add an Authorization header with a user access token.

    Since the call I was trying to do didn't require a user access token, but an application access token (authenticate as application for public Http requests like register, forgot password etc.), I decided to chain the call to get the application access token and the call for the forgotten password and just pass the retrieved application access token to the forgotten password method in my service and set it in the Authorization header there. This code was all fine. The problem was that I had edited the interceptor to check wether there was an Authorization header present and if so do nothing and THAT was the cause of the bug.

    Instead of doing nothing, I should have just returned the request, so it just gets executed without modifications to the header.

    so instead of

    intercept(request: HttpRequest, next: HttpHandler): Observable> {
            if(request.headers.get('Authorization') == null) {
              //Code to add Authorization header
              return next.handle(requestWithAuthHeader)
            }
    }
    

    I had to do the following:

    intercept(request: HttpRequest, next: HttpHandler): Observable> {
            if(request.headers.get('Authorization') == null) {
              //Code to add Authorization header
              return next.handle(requestWithAuthHeader)
            } else {
              return next.handle(request);
            }
    }
    

    Otherwise the request gets intercepted and never executes because it doesn't get returned by the interceptor. The method in my component is subscribed to the result of the service method and thus expects an observable, but nothing ever gets returned because the request got intercepted and the interceptor noticed that an Authorization header was already present (set in the service) so decided to do nothing with the request.

    This explains why I got the error stating that I had provided undefined while a stream (observable) was expected on the subscribe line in my component's method.

提交回复
热议问题