Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, I want to send a 401 response status and update the state in Angular.

The issue I'm facing is that I am unable to retrieve the response object to verify the status. I have attempted various methods, including using an interceptor, logging the error.response.body, and thoroughly examining everything to pinpoint where I might be losing the response object.

Below is some code - any assistance would be greatly appreciated!

Express:

app.get('/update', sessionCheck, function(req, res) {
  res.send('session');
});

function sessionCheck(req, res, next){
    if(req.session.user) {
      next();
    } else {
      console.log('before');
      return res.status(401).send('Unauthorized');
      console.log('after');
    }
}

Angular:

.state('update', {
  url: '/update',
   views: {
    "": {
      templateUrl: 'templates/update.html',
      controller: function($http) {
        return $http.get('/update').then(function(response) {
          console.log('Ok response' + response);
        }, function(error) {
          console.log('Error response' + error.response.body);
        });
      },
    },
    "carousel": {
      templateUrl: "templates/carousel.html"
    },
    "footer": {
      templateUrl: "templates/footer.html"
    }
  }
})

network screen

Answer №1

Have you attempted to implement this using an interceptor?

You could try the following approach:

anyModule.service('yourInterceptor', function($q) {
var service = this;

service.responseError = function(response) {
    if (response.status == 401){
        //do something
    }
    return $q.reject(response);
};

})

It's important to note that we are specifically working with responseError.

In addition, be sure to register your interceptor within a config function:

$httpProvider.interceptors.push('yourInterceptor');

For more detailed information on this interceptor, check out this link:

Capture HTTP 401 with Angular.js interceptor

UPDATE:

You can also register an interceptor like this:

app.factory("YourInterceptor", ["$q", "$rootScope", "$location",
function($q, $rootScope, $location) {
    var success = function(response) {
        //do something
        return response;
    },
    error = function(response) {
        if(response.status === 401) {
                // do something
        }

        return $q.reject(response); //reject on error
    };

    return function(httpPromise) {
        return httpPromise.then(success, error);
    };
}

Then, to register your interceptor within the module's config:

$httpProvider.responseInterceptors.push("YourInterceptor");

Make sure to push the interceptor into responseInterceptors. This method has worked well for me.

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

Pressing the enter key in an AngularJS form does not trigger submission

Having trouble with a login form that won't submit when the user presses enter. While the form works fine when the "Login" button is clicked, hitting enter doesn't trigger submission and leads to some unexpected behavior: The ng-submit associat ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

Gather keyboard information continuously

Currently working with Angular 10 and attempting to capture window:keyup events over a specific period using RXJS. So far, I've been facing some challenges in achieving the desired outcome. Essentially, my goal is to input data and submit the request ...

Using jqgrid to generate a hyperlink that corresponds to the data's value

I am working with a grid setup similar to the one below: $("#list").jqGrid({ url:'listOpenQueryInXML.php', datatype: 'xml', colNames:['Id','name1', 'name2', 'status', 'type' ...

How can you efficiently transfer the expression utilized in v-for from the template to the component code?

How can I extract the expression within the template that is contained in :class? <div v-for="(user, index) in users" :key="index" :class="{'bg-yellow-lighter': infoWindowMarker && infoWindowMarker.position.lat === user.posit ...

accomplishing validation in Angular forms while avoiding the use of the HTML form tag

I'm looking to implement Angular Form Validation without the use of an HTML form. I attempted the following code, but unfortunately, the button remains enabled. <ng-form name="login"> <div class="input-group"> <span class="input ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Configuration object for Webpack is not valid

I encountered an error while using webpack that says: Invalid configuration object. Webpack has been initialized with a configuration object that does not conform to the API schema. - configuration.resolve has an unknown property 'extension&ap ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

Amazon S3 Landing Page Featuring Contact Form

Although S3 is not a fileserver, it serves as an excellent tool for managing static websites. The majority of my projects are 99% static, making it ideal for this particular project. As an AWS Solutions Architect, I am struggling to find the most straightf ...

When the click event is triggered, the second function guess() does not execute

I am currently developing a number guessing application. It consists of two functions, the first one called startGame() works correctly (it receives the maximum number and then disappears by adding the hidden class). However, the second function that is ...

The issue with nodejs multer is that it is successfully receiving the req.file but failing to upload it

multer.js var path = require("path"), multer = require("multer"); const storage = multer.diskStorage({ destination: function(req, file, next){ next(null, '../public/imgs/'); return; }, filename: function(req, file, ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

Error: Model attribute missing in Adonis JS v5 relationship

Recently, I started diving into the Adonis framework (v5) and decided to build a todo list api as part of my learning process. However, I'm facing an issue concerning the relationship between the User and Todo entities. Let me show you the models fo ...

What is the best way to fill HTML tables using an ajax response?

This is a Laravel blade view/page that requires updating without the need to refresh the entire page. The blade.php code functions correctly and retrieves data from a MySQL database, but there seems to be an issue with the AJAX and JavaScript implementati ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

Best practices for securing passwords using Chrome DevTools in React development

React developer tool inspector Is there a way to prevent password values from appearing in the inspector as a state when handling form submissions in ReactJS, especially when using Chrome's React developer tool? ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

The website at localhost with port number 3003 encountered an error with the socket.io connection, specifically in the polling transport mechanism with a reference code of OZxtDFc

Seeking assistance with socket.io chat implementation. I have different routes for various URLs, but encountering transport polling errors after the server initially works. Despite making several changes to ensure that socket uses session middleware func ...

The authentication check with Passport's req.isAuthenticated() function is not functioning properly

I am currently utilizing express-session and passport for authentication purposes. Here is the updated module: passport.use(new LocalStrategy( function(username, password, done) { LamAdmin.findOne({ email: username }, function (err, user) { ...