Search code examples
javascriptnode.jsangulartypescriptangular-http-interceptors

Angular 7 Headers aren't getting set


I'm using Angular 7 and created a interceptor to include auth token in every request.

Here is my interceptor code:

import { Observable } from 'rxjs';

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

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('authToken');
    if (token) {
      request = request.clone({
        setHeaders: {
          authorization: token
        }
      });
    }
    return next.handle(request);
  }
}

The node api to verify auth token:

const jwt = require('jsonwebtoken');

function verifyToken(req, res, next) {
    var token = req.headers['authorization']; // Coming Undefined 
    if (!token)
        return res.status(403).send({ auth: false, message: 'No token provided.' });
    jwt.verify(token, 'top_secret', function (err, decoded) {
        if (err)
            return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
        // if everything good, save to request for use in other routes
        req.userId = decoded.user.email;
        next();
    });
}

module.exports = verifyToken;

When hitting the API with Postman things are working fine but when sent a request using angular code the headers aren't received at node API.

Request header when sent from angular

Request header when sent from Postman

Network Tab Details

Request object sent from browser What could be the possible reason for this kind of strange behavior?


Solution

  • The screenshot you are showing is for a OPTIONS request, required for CORS. You need to enable CORS in nodejs

    First, install the cors module

    npm install cors
    

    Then use it in your nodejs backend

    var cors = require('cors');
    app.use(cors());