I'm having trouble finding the solution to setting a token in my request header

I have been following a tutorial in a book to build the authentication for my app. However, I am facing an issue where after logging in correctly, I am unable to set the token back into the request. The error message that I receive is:

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

Any assistance with this problem would be greatly appreciated.

File: authService.js

angular.module('authService', [])

// ===================================================
// auth factory for login and user information handling
// dependencies: $http for API communication, $q for promise objects, AuthToken for token management
// ===================================================

.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};

authFactory.login = function(username, password) {
return $http.post('/api/authenticate', {
username: username,
password: password
})
.success(function(data) {
console.log(data);
AuthToken.setToken(data.token);
return data;
});
};

authFactory.logout = function() {
AuthToken.setToken();
};

authFactory.isLoggedIn = function() {
if (AuthToken.getToken())
return true;
else
return false;
};

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 managing tokens
// dependencies: $window for client-side token storage
// 
// 
// ===================================================

.factory('AuthToken', function($window) {
var authTokenFactory = {};

authTokenFactory.getToken = function() {
return $window.localStorage.getItem('token');
}; 

authTokenFactory.setToken = function(token) {
if (token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
};

return authTokenFactory;
})

...

File: app.js

var app = angular.module('userApp', [ 
'ngAnimate', 'app.routes', 'authService', 'mainCtrl', 'userCtrl', 'userService']);

app.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});

app.controller('mainController', function($http) {
var vm = this;

vm.message = 'Hey! Message';

$http.get('/api/users')
.then(function(data) {
vm.users = data.users;
});
});

Answer №1

When creating a custom interceptor factory, you need to ensure that the correct token is added to the headers of the request.

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

Make sure to change AuthToken.getToken; to AuthToken.getToken();

If you receive an error message stating that you are passing a function into the header instead of a value, it means that you need to provide a valid value for the HTTP header field.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Revamping the jQuery eye pupil tracker via the mousemove functionality

My goal with this code is to create an eye that follows the user's cursor direction. I found inspiration from this code snippet: https://codepen.io/J-Roel/pen/wWGNQN. However, since it was written in jQuery, I decided to convert it to vanilla JavaScri ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

Unlocking Family Information on Facebook: A Guide to Using the Facebook Graph API

Here is the code to fetch family details: <?php if ($user) { try { $access_token = $facebook->getAccessToken(); $user_profile = $facebook->api('/me'); $family = $facebook->api('/me/family'); } catch ( ...

Retrieve an image located outside of a container

I have multiple SVGs inside separate div elements. <div id="divA"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="10" y="10" height="130" width="500" style="fill: #000000"/> ...

Leveraging JQueryUI for an audio Seek feature, and dynamically connecting a fresh slider to the <audio> element whenever a song is swapped out

Thanks for taking a look at my question. The code snippet can be found HERE. I'm in the process of creating an audio player to handle multiple songs on a single page using JQueryUI Slider and HTML5 Audio, with one Audio element and several sliders. ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...

Is there a way to retrieve data from three different Bookshelf.js models in a single query?

Three tables are in my database: User, UserDrink, and VenueDrink Here is a preview of the sample data: User id | name | gender | -------------------- 1 | John | male | 2 | Jane | female | UserDrink id | count | user_id | venue_drink_id 1 | 3 | ...

"Making AngularJS $resource calls to Laravel backend for data submission - POST and PUT methods

I'm struggling with sending REST requests using $resource to my Laravel application. One issue I encountered was that the $resource POST method sends Request Payload data, which I couldn't read in Laravel. To work around this, I had to transform ...

Exploring the feature of setting the checked state in Radio.Group using Antd

I am dealing with dynamic data that needs to be displayed in a radio button format. One of the challenges is comparing the dynamically generated id with the active radio id and setting it as checked using Radio.Group. Unfortunately, the current code is no ...

Leverage the power of Web Components in Vue applications

Currently, I am attempting to reuse Web Components within a Vue Component. These Web Components utilize the template element for formatting output. However, when I insert them into the Vue Template, they are either removed from the DOM or compiled by Vue. ...

Is there a PHP script available to verify the status of FTP servers and determine if

I am in need of creating a PHP script that is triggered by a setInterval("ajaxrequest('ftp.php', 'context')", 1000) function. The PHP script itself is quite simple. It consists of an array containing FTP addresses. The script loops thro ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

Special characters like greater/less than signs have not been properly encoded

I am currently facing an issue in regards to escaping strings on the server side (using Node.js & Express.js) that contain greater/less than signs (<, >). Below is the code snippet I'm using on the server side: socket.on('message', fu ...

Angular Grid Event Triggered by Checkbox Selection in the Header

I am currently utilizing ng-grid from AngularUI-Grid, where I have implemented a checkbox for row selection. Interestingly, it also provides a checkbox in the header. If a user selects the checkbox in the header, I need some event or method to trigger in ...

Utilizing Bootstrap Modal to trigger an Action Result function when a button is clicked

I could use some assistance. In my current setup, I have a file picker that loads a file into a specific table in my database. When the user clicks a button, a bootstrap modal pops up to ask if they are uploading more files. This is how it looks in my vi ...

Having difficulty adding a Dropdown Menu in a Pop-up Box

I am trying to incorporate a select menu inside of a popover, but every time I attempt to do so, the popover content block remains blank. The popover is associated with a side menu item called "Date History". Below is the code snippet I am using to constr ...

Exploring the world of web programming

Looking for top-notch resources to learn about JavaScript, AJAX, CodeIgniter and Smarty. Any recommendations? ...

Using AJAX to dynamically update a div's class following a POST request

Upon double clicking a row, I am attempting to trigger the function outlined below. Despite my efforts, I have not been able to update the div class with any changes. function book(id) { $.ajax({ type: "POST", url: "ajax_servlet. ...

Sinon.stub functions as expected in karma and mocha when using Chrome, however it encounters issues when running in head

In my current project with AngularJS, I have implemented a feature where scrolling on an element triggers the scrollTop() function to determine if another method needs to be executed. I created a sinon.stub for this purpose: scrollTopStub = sinon.stub($. ...