The initial $http POST in Angular ends up hitting the error path within the .then function despite the successful execution of the

Something strange is happening to me. This peculiar behavior occurs only on the initial POST request. However, when I resubmit the form, the subsequent requests work perfectly fine.

The first $http post call leads to the error function in .then, even though the backend call to the server successfully completes end-to-end (status -1). If I redo the same request, it smoothly goes through the success path in .then.

In my application, I am utilizing Angular's ng-view, ng-route, and ng-controller constructs to connect everything.

Thank you for your assistance.

$http({
    url: "/api/v1/login",
    method: "POST",
    headers: { "Content-Type": "application/json" },
    data: {
        username: uname, 
        password: pword
    }     
 })
 .then (
    function (success) {
        $scope.content = success.data;
        if ($scope.content.status == "Login successful") {
            window.location.href="/apps/home.html"; 
        } else {
            alert("Login failed");
            window.location.href="#login";
        };
    },
    function (error) {
        alert("Call error = " + error.status);
        window.location.href="#login";
    }
 ); 

Answer №1

Substitute the direct use of window.location with AngularJS' $location service. Invoking window.location within a $q service's fulfillment handler may lead to an internal error in AngularJS.

To delve deeper, you can refer to this informative discussion on StackOverflow: StackOverflow: login using angular js and $http request

Answer №2

Just wanted to provide an update on this. It turns out that the problem was caused by having Action="#" in the HTML form. Once I removed that, everything started working properly again.

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

Creating functionality with a native JavaScript plugin within a directive and test suite

I have a custom JavaScript plugin that is integrated within a directive and utilized in an Angular manner. Snippet of the directive, export default function () { 'use strict'; return { restrict: 'E', scope: { map: &apo ...

HTML5 failing to load button

<!DOCTYPE html> <html> <head> <title>Greetings Earthlings</title> <script src="HelloWorld.js" /> </head> <body> <button onclick ="pressButton()" >Press Me!</button> ...

How to prevent VueJS observer from monitoring a temporary variable

My VueJS and Observer objects are causing me trouble. I am encountering an issue where I assign a part of my object to a temporary variable for later use, update the original part with new data, and then revert it back to its original state after 8 seconds ...

Geoserver does not have the 'Access-Control-Allow-Origin' header

map.on('singleclick', function (evt) { document.getElementById('info').innerHTML = "Looks like you need to redo this :) !!!"; var view = map.getView(); var viewResolution = view.getResolution(); var source = hcm.getSource(); var url = s ...

Creating and modifying arrays using AngularJS

There is a feature in my application where clicking the Add button triggers a modal to appear. The modal contains 3 input boxes for filling in details. Once the information is saved, a list is displayed on the main page with the title of the newly added it ...

Safeguard your contact information on the screen

On my classified website, I have concerns about the contact numbers being displayed as plain text in the product details page. This makes them visible to search engines. Is there a way to protect or display phone numbers as images to keep them hidden fro ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

Validating optional fields in React

My registration form includes the following fields: Name Email Password Confirm password Optional field Select role (student, professor, secretary) Here's what I'm trying to achieve: If I want to create a user with a student role, the optional ...

Aggregate the JSON data by grouping and calculating the total value

Looking to organize a set of JSON values by grouping them based on different geographical regions. Identified,Proposal Submitted,QO under Evaluation,Negotiation & Contracting,Closed Lost,Closed Won are all grouped according to count and pipelinevalue ...

Tips on exposing promise data object in the controller and transferring data from the promise to a new function

After creating an angular controller and service to extract data from a JSON file, everything seemed to be working smoothly. However, I encountered an issue when attempting to assign this data to a new object. My goal is to implement a new function within ...

Implementing JavaScript to assign a symbol to several <span> elements with identical ids

I have a looping span element on my page that is generated based on the number of records in a database table. The appearance of the span can vary, displaying either one or multiple instances. Each span has the following structure: <span class="add-on" ...

The Shell Application is not refreshing React HtmlElement Micro Front end

I am currently facing an issue when trying to inject the following React MFE into another Angular shell application. The MFE loads successfully the first time, but if it is hidden or removed from the DOM and then reloaded, it fails to load. Could you plea ...

React Native: Avoiding Infinite Loops in useEffect

I am facing an issue where my app goes into an infinite loop because pointsData is inside the useEffect function. How can I resolve this situation? function useGetPoints() { const [pointsData, setPointsData] = useState<PointTbleType[]>([]); ...

The authentication token interceptor fails to capture the request/response of a new route

I have been working on implementing JWT authentication for my Node.js, Express, and AngularJS application. I successfully generated the token and stored it in the localStorage. Following a tutorial on this website, I implemented the authInterceptor in an A ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

Issue with Tweening in Three.js: Initial value does not change

Having trouble with tweening my camera position. I've set up a Codepen with minimal code to showcase the issue, complete with annotations and plenty of console.log() statements for debugging purposes. Check out the Codepen The starting point of my c ...

Getting image blob data with Cropper Js in a Laravel controllerNeed help on how to get image blob data

I've been working with Cropper.js and Laravel. I managed to crop an image, put it into FormData, and send it to the Laravel controller using jQuery Ajax. However, I encountered a problem where I am not receiving any data in the controller, only an err ...

Database entry does not appear in Internet Explorer until the browser is completely shut down and reopened

Currently, I have a form with two dropdowns. Selecting an option from the first dropdown automatically populates the second dropdown. Everything works well except for a minor issue I observed recently. When I add a new item to the second dropdown, it gets ...