【问题标题】:Can not seem to figure out how to set a token in my request header似乎无法弄清楚如何在我的请求标头中设置令牌
【发布时间】:2015-08-30 05:40:21
【问题描述】:

我正在学习一本书教程,我目前正在为应用程序构建身份验证。每当我正确登录时,我似乎都无法将令牌设置回请求中。我得到的错误是:

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

【问题讨论】:

    标签: javascript angularjs token access-token mean-stack


    【解决方案1】:

    在自定义拦截器工厂中

     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.
    

    【讨论】:

    • 谢谢!我仍然不清楚为什么这会奏效。我对 js 和 Angular 很陌生,所以请原谅我缺乏专业知识。
    • 因此,当您执行 AuthToken.getToken 时,它会返回一个方法实例,但实际上并未调用该方法。
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2020-11-14
    • 2011-11-28
    • 2014-05-19
    • 2023-02-11
    • 2014-07-28
    相关资源
    最近更新 更多