AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code.

Here is the script I am working with:

$http.post('/authlogin', {
    email: $scope.userdata.email,
    password: $scope.userdata.password
}).then(function(response) {
    console.log(response);
    if (response.status == 400) {
        $scope.errormsg = response.data;
    }
    if (response.status == 200) {
        window.location = '/admin';
    }
});

Everything functions properly for a 200 OK response. However, when the login fails and the API responds with a 400 Bad Request, it seems like the anonymous function with the response isn't being called. Most checks for statuses 400, 200, 201, etc., work flawlessly everywhere else, but not with 400.

This is the error displayed in the browser console by AngularJS (sensitive data has been prettified and removed):

Possibly unhandled rejection:
{
    "data": "Invalid email/password combination.",
    "status": 400,
    "config": {
        "method": "POST",
        "transformRequest": [null],
        "transformResponse": [null],
        "jsonpCallbackParam": "callback",
        "url": "/authlogin",
        "data": {
            "email": "####",
            "password": "***"
        },
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        }
    },
    "statusText": "Bad Request"
}

As I am not an expert in angular.js, I would greatly appreciate an explanation of this behavior along with a potential solution.

My goal is to present the user with an error message that is returned in data.

Answer №1

When using $http, the returned promise is resolved by executing the first anonymous function. If the promise is rejected, the second anonymous function is called. This method should effectively handle the task at hand.

$http.post('/authlogin', {
    email: $scope.userdata.email,
    password: $scope.userdata.password
}).then(function(successCallback) {       
    if (successCallback.status == 200) {
        window.location = '/admin';
    }
}, function(errorCallback){
    if (errorCallback.status == 400) {
        $scope.errormsg = errorCallback.data;
    }
});

To explore further examples, refer to the documentation

For a comprehensive understanding of promises, check out this resource

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

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

Using Styled Components to achieve full width for input tag in relation to its parent

I am working with an input field that has a specific width set. My goal is to increase the width of this input field to 100% by selecting it from its parent component. Is there a way to achieve this without passing an explicit width prop in the styled c ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

Troubleshooting 'Warning: Prop `id` did not match` in react-select

Having an issue with a web app built using ReactJs and NextJs. I implemented the react-select component in a functional component, but now I'm getting this warning in the console: Warning: Prop id did not match. Server: "react-select-7 ...

Performing a Node.js PUT call with specified parameters

Attempting to send a PUT request using the 'request' function to the following URL: request({ uri: 'http://apiurl.url/1.0/data?token=' + APItoken, method: 'PUT', data: [{ ...

When attempting to access the requested resource in AngularJS, there is no 'Access-Control-Allow-Origin' header present

When attempting to run my web-service from within my code, I encounter the following error message: "XMLHttpRequest cannot load http://mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:/ ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

The "405 method not supported" exception pops up exclusively for Angular/HTML/JSP resources within a Spring Boot application

My Spring Boot and AngularJS application is encountering an issue when trying to access a REST service with a POST method. Interestingly, I am able to successfully hit the service wherever POST is configured for request mapping. However, when attempting t ...

Encountering a DiscordAPIError[10062] when attempting to retrieve user points from the database due to an unknown interaction

content: "Congratulations, you have been successfully verified!", ephemeral: true, }); } } else if (interaction.customId === "giverole") { const userPoints = await findUser(interaction.member ...

Tips for merging conditional and data binding classes in AngularJS

In order to dynamically apply different classes based on expressions in your AngularJS templates, you can make use of the ng-class directive. Here is an example: <div ng-class="{'class1' : expression1, 'class2' : expression2}"> ...

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

Update the value after verifying the element

I am trying to retrieve data from my database and update the values when an element is clicked (accepting user posts). The code I have written seems to work, but I encounter an error stating that props.actions is not a function when clicking on an element. ...

I'm looking to configure @types for a third-party React JavaScript module in order to use it with TypeScript and bundle it with webpack. How can I accomplish this?

Imagine you have a third-party npm package called @foo that is all Javascript and has a module named bar. Within your TypeScript .tsx file, you want to use the React component @foo/bar/X. However, when you attempt to import X from '@foo/bar/X', y ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...