When making an $http request, the success function will still receive a response even if the status code is

In my Angular application, I encountered an issue with the login function. When incorrect credentials are entered and the response returns a status of 401: Bad Credentials (confirmed by response.status = 401), it still triggers the success message.

As a result, I receive a notification saying "Success login" followed by an HTML error page in my interceptor. This situation is confusing me, as I'm unsure how I ended up in this messy state.

this.getTokenCustom = function (user) {
    $http.post('/login',
        JSON.stringify({username: user.username, password: user.password}))
        .then(
            function success(response) {
                localStorage.setItem('token', response.data.token);
                $.notify({message: "Success login"},{type:'success'});
                $state.go('roles');
            },
            function error(data) {
                console.log(data);
                $.notify({message: data.data.message},{type:'danger'});
            }
        );
};

UPD

    this.getTokenCustom = function (user) {
    $http.post('/login',
        JSON.stringify({username: user.username, password: user.password}))
        .then(
            function success(response) {
                localStorage.setItem('token', response.data.token);
                $.notify({message: response.status + " Success login"},{type:'success'});
                $state.go('roles');
            },
            function error(data) {
                console.log(data);
                $.notify({message: data.data.message},{type:'danger'});
            }
        );
};

Answer №1

The probable reason for this issue could be a custom interceptor that is not effectively managing error situations.

You can refer to the following article for guidance:

As stated in the article:

When dealing with requestError or responseError for an interceptor and wanting to pass on the error to the next handler, you must utilize the promise API to reject the message:

$httpProvider.interceptors.push(function($q) {
    return {
        'requestError': function(rejection) {
            // handle same as below
        },

        'responseError': function(rejection) {
            if (canRecover(rejection)) {
                // if recovery is possible, avoid calling q.reject()
                // as it will proceed to success handlers
                return responseOrNewPromise;
            }

            // !!Important Ensure to use the promise API's q.reject()
            // for proper implementation of this interceptor
            // otherwise, the response will reach the caller's success handler
            return $q.reject(rejection);
        }
    };
});

An analogous problem to yours was documented on Angular's Github repository, wherein the issue stemmed from a custom interceptor failing to manage error scenarios correctly.

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

Passport session is lost following oauth callback

Developing a hybrid app using Ionic, Angular, nodejs, etc. After the user logs in with their email and password, they want to include 3rd party authentication for their account. Once the user is serialized into session, we verify their authorization sta ...

Uncertain about the ins and outs of AJAX

I am a complete beginner in web development. Although I have studied JavaScript and HTML through books, my understanding is still limited. I have never worked with AJAX before and find most online examples too complex for me to follow. My goal is to crea ...

Using Angular 1.x directive with a shared scope and a parent controllerAs approach

I'm currently working on a directive that needs to call a specific method declared within the parent controller. Feel free to check out my Plunker example here Within the parent controller, I am utilizing the 'controller as vm' syntax. How ...

Searching for a method to retrieve information from an API using jQuery in Node.js?

I'm currently working on fetching data from an api to display on the front-end. This is my server-side code - app.get('/chats',function(req,res){ User.find({}).exec(function(err,user){ res.send(user); }); }); On the clie ...

Incorporating a lasting element into the _app.js file of Next.js

I am currently experimenting with my first Nextjs app and encountering difficulties when trying to incorporate a persistent sidebar. While looking for solutions, I came across Adam Wathan's article on persistent layouts in Nextjs. However, it appears ...

React Native / Redux - The "Cannot update during an existing state transition" error occurs when attempting to update

Currently working on an app using React Native and Redux, I've encountered a snag in the implementation process. An error message pops up saying setState cannot update during an existing state transition (such as within render or another componen ...

Having trouble retrieving the props of a React component within a styled.div component

Transitioning from Angular to React, I am still getting the hang of things and encountering an issue with accessing a property of a styled component passed into it. The error message that pops up is: /src/chat/Container.js Line 115:5: 'cssOverride ...

Adjusting the size and appearance of ngDialog

Currently using the Ionic framework and encountering an issue with popup sizing. $scope.dialog = ngDialog.open( { template: 'popup.html' , className: 'ngdialog-theme-default' , controller: 'MyCtrl' ); By default, the popup o ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

Facing CORS issue when trying to use the app on a device without network activity, although it works fine on

Currently, I am in the process of developing an Ionic app. Interestingly, the app runs smoothly in the browser; however, when it comes to running it on the device, the HTTP requests fail to load. Upon inspecting the app using Safari remote debugging, no er ...

Another network request within the ng-repeat loop

My Angular application needs to call web services from two different URLs. The first URL abc.com/student/3 provides a list of students, while the second URL abc.com/parent/idofStudent3 gives the parent's first name when passed the student ID. I have ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

Positioning elements in CSS with a rolling ball animation

Introduction I have a project in progress to develop a Bingo game. One of the current tasks involves creating a CSS animation that simulates a rolling ball effect. The objective is to make it appear as though a ball drops from a wheel and rolls from righ ...

Exploring the Force-Directed Graph Demo on bl.ocks.org

I don't have much expertise in javascript, jquery, or json. My objective is to create a graph using the force-directed graph example from bl.ock.us. 1) I wrote a python script to generate the necessary json data. 2) I noticed others were us ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

When the jGrowl function is triggered, it disrupts the functionality of the thickbox in conjunction with UpdatePanel

Whenever a link is clicked, I trigger a thickbox like this: <a href="createContact.aspx?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=400&width=550&modal=true" title="Add a new Contact" class="thickb ...

Limiting the options available in dropdown menus

In my HTML code, I have two drop-down lists that look like this: <select name="from" id="abs-from-1"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> ...

Puppeteer is not compatible with VPS hosting on DigitalOcean

I'm currently using a droplet on DigitalOcean and encountering the following error: (node:5549) UnhandledPromiseRejectionWarning: TimeoutError: Navigation Timeout Exceeded: 300000ms exceeded at Promise.then (/var/www/screenshot/node_modules/puppe ...

AngularJS ngRepeat with ngSwitch implementation

I need help with formatting the track list: Disc 1 track[1] track[n] Disc 2 track[1] track[n] Can someone guide me on where to insert these headers? <h3>Track List:</h3> <div ng-repeat="track in tracks"> <div ng-switch on="tr ...

The elegant-admin template's mobile navigation toggle is missing

I recently downloaded an admin theme and added the CSS to my Django static files. However, after doing so, the mobile toggle feature disappeared. I double-checked all the CSS and JS links in the index template, and they are correctly linked to the paths, b ...