代码之家  ›  专栏  ›  技术社区  ›  Lynob

HTTP拦截器:您在需要流的位置提供了“未定义”

  •  0
  • Lynob  · 技术社区  · 6 年前

    我正在使用Angular6,试图实现HTTP拦截器,它给了我 ou provided 'undefined' where a stream was expected 尝试登录时。我没有JWT代币,我有一个 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

      onLogin() {
        this.auth.login(this.username, this.password).subscribe(data => {
          if (localStorage.getItem('data') === null) {
            localStorage.setItem('data', JSON.stringify(data));
          }
          const token = data.headers.get('x-session');
          const expiry = data.headers.get('x-session-expiry');
          localStorage.setItem('token', JSON.stringify(token));
          localStorage.setItem('token-expiry', JSON.stringify(expiry));
          this.router.navigate(['']);
        }, err => {
          console.log(err);
        });
      }
    

    如何修复错误?我想如果我使用的是JWT,就不会有错误,因为大多数文章都推荐上面显示的方法或类似的方法。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Lynob    6 年前

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

    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语句,如果用户登录,请添加令牌,否则不要添加它。