HTTP拦截器:您提供了“未定义”的预期流

时间:2018-08-24 00:37:13

标签: angular angular6 angular-http-interceptors

我正在使用角度6,试图实现http拦截器,尝试登录时会给我<section id="welcome" class="bg-primary d-flex flex-column"> <h1 class="position-absolute">Positions</h1> <div class="container text-center my-auto"> Centered content </div> </section> 。我没有jwt令牌,我有ou provided 'undefined' where a stream was expected

x-session

interceptor.ts

constructor(private injector: Injector) { } intercept(req, next) { const auth = this.injector.get(AuthService); const token = auth.getToken(); if (token) { const tokenizedReq = req.clone({ setHeaders: ({ 'Content-Type': 'application/json', 'x-session': token }) }); return next.handle(tokenizedReq); }

login service

login(username, password) { const data = { username: username, password: password }; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post(this.login_url, data, { headers: headers, observe: 'response' }); } getToken() { return JSON.parse(localStorage.getItem('token')); }

login component

如何解决该错误?我想如果我使用的是jwt,就不会有错误,因为大多数文章都建议使用上面显示的方法或类似的方法。

1 个答案:

答案 0 :(得分:0)

我不知道我的解决方案是否是最好的,但似乎可行,如果有人有更好的解决方案,我会接受的。

interceptor

constructor(private injector: Injector) { }
  intercept(req, next) {
    const auth = this.injector.get(AuthService);
    const token = auth.getToken();
    if (token) {
      const tokenizedReq = req.clone({
        setHeaders: ({
          'Content-Type': 'application/json',
          'x-session': token
        })

      });
      return next.handle(tokenizedReq);
    } else {
      const tokenizedReq = req.clone({
        setHeaders: {
          'Content-Type': 'application/json'
        }
      });
      return next.handle(tokenizedReq);
    }
  }

login service

 login(username, password) {
    const data = {
      username: username,
      password: password
    };
    return this.http.post(this.login_url, data, { observe: 'response' });
  }

因此请注意,我添加了else语句,如果用户已登录,则添加令牌,否则,请勿添加令牌。