javascript - Simple authentication of REST get call with request interceptors of an Angular service -


i want pass in username , password combination needed make rest call api.

controller.js

var app = angular.module('myapp', []);  //the service put interceptor configuration on (not on $http method calls) app.factory('getcallsapi', ['$http', function($http) {     return {         get: function(callback) {             $http.get(/* rest uri */).success(function(data) {                 callback(data);             });           }     } }]);  var interceptor = function($q) {     return {         request: function(config) {             //todo: pass in username , password (hardcoded) through authentication          },         requesterror: function(rejection) {          },         response: function(config) {             //todo: add cross origin headers          },         responseerror: function(rejection) {          }     } }  app.config(['$httpprovider', function($httpprovider) {       $httpprovider.interceptors.push(interceptor); }]);  myapp.controller('appcontroller', ['$scope','getcallsapi', function($scope, getcallsapi) {   getcallsapi.get(function(data) {     console.log(data);   }); }]); 

i receiving 2 errors in console. first 401 status unauthorized access , error cross origin headers not found on requested resource. cannot put x origin headers on requested resource myself because dont have rights edit response of api.

not speaking cross origin issue, here how add request headers. in case, pass in token stored in localstorage. bind value angular constant , inject interceptor service:

.constant('auth_token', localstorage.getitem('myapp.authtoken')) 

and in interceptor:

    var interceptor = function ($q) {         return {             request: function (config) {                  if (auth_token) {                     config.headers['authorization'] = 'token ' + auth_token;                 }                 return config;             }         }     } 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -