znight znight - 3 months ago 35x
Javascript Question

Getting TypeError: Cannot read property 'data' of undefined, when trying to include an AuthInterceptor service I made with AngularJS

So yeah, i'm getting this weird TypeError when I try to include my AuthInterceptor into my index.html. I get this error when I try to load localhost:8080/#/login, which shows my login page. Not included here because it's not relevant. My login page renders successfully when I remove the link to my AuthInterceptor in index.html.


function AuthInterceptor() {
this.request = function(config) {
config.headers = config.headers || {};
return config;
this.response = function(response) {
if (response.status === 401) {
alert('STATUS 401!');
return response;


.service('AuthInterceptor', AuthInterceptor)
.config(function ($httpProvider) {


<!doctype html>
<script src="js/app/angular.js"></script>
<script src="js/app/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.4/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.css">
<script src="js/app/app.js"></script>
<script src="js/app/controllers/LoginController.js"></script>
<script src="js/app/controllers/MainController.js"></script>
<script src="js/app/services/AuthInterceptor.js"></script>
<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Angular Application</title>
<body ng-app="app">

<div ui-view></div>



The problem is that in your interceptor, you only pass the response when you get a 401 error, the goal of an interceptor is to run code either before or after a request, and to pass the error/response along.

You should consistently pass them along. The error that's logged to the console just means that a request you make in another part of the app fails because as you don't pass the response, the data parameter in the promises's .then() is not defined and it throws an error.

this.response = function(response) {

  if (response.status === 401) {

    alert('STATUS 401!');
    return response;

  return response; // Always return response

Hope it helps