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

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

What is the best way to add numerous images to a Laravel platform via ajax using pure javascript?

I am currently working on a form where users can upload one or more photos to the server using ajax. Sometimes, users may not upload any photos at all. How can I efficiently send the data from the file input to the server in the background? Below is the r ...

Notation for JavaScript UML component diagrams

When creating connections between entities on a UML diagram, the standard notation is the ball-and-socket/lollipop method. Each pair should include the interface implemented. However, since my project is in JavaScript and doesn't have interfaces, I am ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

Looking for the most effective method to establish a connection between OracleDB and SQLite using node.js?

Recently, I have embarked on a small project that has introduced me to the world of node.js, oracleDB, and sqlite. While these technologies are new to me, I have successfully implemented an oracleDB connection to fetch data from tables. However, I also hav ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

unable to auto-populate drop-down selection based on selected value in AngularJS

Currently, I am implementing a drop-down within an ng-repeat loop in AngularJS. Here is the HTML code snippet: <select class="form-control" ng-model="l.Language" ng-change="languageChange($index, l.Language)" ng-options="L.ID as L.LanguageDDL for L i ...

The JQuery datepicker fails to display the current date

I am experiencing an issue with the datepicker on my webpage. While it is working correctly, the default date being displayed is '01/01/2001' instead of '11/23/2012', as I intended. Here is the jquery code I am using: $(":inpu ...

Modify the name of the selected option value

I am working on an html code where I need to replace the values 0, 1, and 2 with USA, Australia, and Canada respectively. I also need to know the name of these values in my MySQL database. Thanks! HTML <form method="post" id="countriesForm" name="cou ...

The Google Picker API encounters a server error when attempting to retrieve the OAuth token after being released as a private add-on

Recently, I encountered a puzzling issue with my script that utilizes the Google Picker API. During testing, everything worked flawlessly until I decided to publish it as a private add-on. From that point on, the script's getOAuthToken function starte ...

Ways to trigger an onClick event of one div based on the presence of another div

I'm looking to execute a function when a specific type of button is clicked on my HTML page. I have approximately 10 buttons on the page and I've written the following code to call a function when a button is clicked: $('.divname').ea ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

What steps are involved in setting up a local server on my computer in order to create an API that can process http requests from Flutter?

New to API creation here, so please be patient. I plan to eventually host my API on a more robust server, but for now, I want to get started by setting something up locally on my PC to work on backend functions. The API goals include: Verify incoming requ ...

Marker on Google Maps in Dark Mode is not displaying properly

I have integrated a custom map into my website using the npm module called google-map-react. The provided tutorial demonstrates how to implement a basic marker on the map, and you can find it here: . Here is an example of what it should look like: import ...

Encountering an unauthorized error when using the client-side fetch call in an Express React JS

Looking to implement JWT authorization that spans both the frontend and backend of my app, with the exception of one endpoint that needs to be authorized only when called from the front end. Here is my frontend code: fetch('http://localhost:3000/ima ...

Is the presence of unhandled requests in Node.js linked to a depletion of resources?

Whenever an issue arises and I forget to call res.end, res.json, etc., the server does not respond which suggests that there is something still pending. Is it necessary for me to address this? What are the implications if this occurs frequently? ...

Using a REST API to make a POST request that calls a function and passes

Within my index.js file, the following code is implemented: app.post("/token", function (req, res) { var token = req.body createToken(token); }); This functionality is then exported by token.js const createToken = (token) = (req, res) => ...

Jest snapshot tests using react-test-renderer encounter null references in refs

Having an issue with manually initializing the Quill editor in componentDidMount and encountering Jest test failures. It seems that the ref value I am receiving is null in jsdom. There is a related issue here: https://github.com/facebook/react/issues/7371, ...