Search code examples
angularangular6angular-http-interceptors

HTTP interceptor: you provided 'undefined' where a stream was expected


I'm using angular 6, trying to implement http interceptor, it's giving me ou provided 'undefined' where a stream was expected when trying to login. I don't have a jwt token, I have an 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);
    });
  }

How to fix the error? I guess if I was using jwt, there would be no error because most articles recommend the way shown above or something similar.


Solution

  • I don't know if my solution is the best, but it seems to be working, if anyone has a better solution, I'll accept his.

    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' });
      }
    

    So notice that I added an else statement, if the user is logged in add the token, else, don't add it.