Не могу понять, как установить токен в заголовке моего запроса

0

Я следую учебному руководству, в настоящее время я создаю аутентификацию для приложения. Всякий раз, когда я вхожу в систему правильно, я, похоже, не могу вернуть токен в запрос. Ошибка, которую я получаю:

Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function () {
        return $window.localStorage.getItem('token');
    }' is not a valid HTTP header field value.

Любая помощь будет принята с благодарностью

authService.js

angular.module('authService', [])

// ===================================================
// auth factory to login and get information
// inject $http for communicating with the API
// inject $q to return promise objects
// inject AuthToken to manage tokens
// ===================================================

.factory('Auth', function($http, $q, AuthToken) {
	// create auth factory obj
	var authFactory = {};
	// login user
	authFactory.login = function(username, password) {
		// return promise obj and its data
		return $http.post('/api/authenticate', {
			username: username,
			password: password
		})
		.success(function(data) {
			console.log(data);
			AuthToken.setToken(data.token);
			return data;
		});
	};
	
	// logout user by clearing token
	authFactory.logout = function() {
		AuthToken.setToken();
	};
	
	// check if user is logged in
	// checks for local token
	authFactory.isLoggedIn = function() {
		if (AuthToken.getToken())
			return true;
		else
			return false;
	};
	
	// get logged in user
	authFactory.getUser = function() {
		if (AuthToken.getToken())
			return $http.get('/api/me', { cache : true});
		else
			return $q.reject({ message : 'User has no token.'});
	};
	
	
	
	return authFactory;
})
// ===================================================
// factory for handling tokens
// inject $window to store token client-side
// 
// 
// ===================================================
.factory('AuthToken', function($window) {
	var authTokenFactory = {};
	
	// get token out of local storage
	authTokenFactory.getToken = function() {
		return $window.localStorage.getItem('token');
	};
	// function to set token or clear token
	 // if a token is passed, set the token
	 // if there is no token, clear it from local storage
	 
	 authTokenFactory.setToken = function(token) {
		 if (token)
		 	$window.localStorage.setItem('token', token);
		else
			$window.localStorage.removeItem('token');
	 };
	
	return authTokenFactory;
})
// ===================================================
// application configuration to integrate token into requests
// ===================================================
.factory('AuthInterceptor', function($q, $location, AuthToken) {
	var interceptorFactory = {};
	
	// this will happen on all http requests
	interceptorFactory.request = function(config) {
		// grab token
		var token = AuthToken.getToken;
		// if token exists add it to the header as x-access-token
		if (token)
			config.headers['x-access-token'] = token;
			
			return config;
	};
	
	// happens on response errors
	interceptorFactory.responseError = function(response) {
		// if 403 from server
		if (response.status == 403) {
			AuthToken.setToken();
			$location.path('/login')
		}
		//return the errors from server as promise
		return $q.reject(response);
	};
	
	return interceptorFactory;
});

app.js

var app = angular.module('userApp', [ 
	'ngAnimate', 'app.routes', 'authService', 'mainCtrl', 'userCtrl', 'userService']);
// app config to integrate token into req
app.config(function($httpProvider) {
	// attach our auth interceptor to the http reqs
	$httpProvider.interceptors.push('AuthInterceptor');
});

app.controller('mainController', function($http) {
	// Bind this to view / vm-view model
	var vm = this;
	
	// define variables and objects on this
	// this lets them be available to our views
	// define a basic variable
	vm.message = 'Hey! Message';
	
	$http.get('/api/users')
	.then(function(data) {
		// bind users to vm.users
		vm.users = data.users;
	});	
});
Теги:
mean-stack
access-token
token

1 ответ

0
Лучший ответ

В специализированном заводе-перехватчике

 interceptorFactory.request = function(config) {
            // grab token
            var token = AuthToken.getToken;
            // if token exists add it to the header as x-access-token
            if (token)
                config.headers['x-access-token'] = token;

                return config;
        };

изменить AuthToken.getToken; к AuthToken.getToken();

и ваша ошибка была совершенно ясна, что вы передавали функцию в заголовок вместо значения

Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function () {
        return $window.localStorage.getItem('token');
    }' is not a valid HTTP header field value.
  • 0
    Спасибо! Мне до сих пор неясно, почему это сработало. Я довольно новичок в js и angular, так что прости меня за недостаток опыта.
  • 0
    поэтому, когда вы делаете AuthToken.getToken, он возвращает экземпляр метода, который фактически не вызывает метод.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню