Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost.

My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page and causing my application to fail.

What I am trying to achieve is to open the redirected page, log in successfully, and then be redirected back to the originally requested page (assuming this should be handled by the external page).

Although my code isn't very advanced yet, here it is:

var app = angular.module('webUI', [])
app.controller('Rest', function($scope, $http) {
    $http.get('https://test/rest/monitoring')
        .then(function successCallback(response) {
                $scope.rest = response.data;
            }, function errorCallback(response){

            });
});

Is there a straightforward Angular function that I may be overlooking, which could help me achieve what I'm aiming for?

Edit: Here is the error message that appears in my browser console (Chrome->F12):

The redirect from '' to '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Answer №1

To ensure proper redirection, remember to insert your desired URL path into the successCallback function by using $location.path('/newURL'). Don't forget to also include the necessary dependencies for $location in your controller.

      let app = angular.module('webApp', [])
      app.controller('API', function ($scope, $http, $location) {
          $http.get('https://api/data')
              .then(function onSuccess(response) {
                  $scope.data = response.data;
                  $location.path('/newURL');
              }, function onError(response) {

              });
      });

Answer №2

Consider incorporating angular routing into your project for better navigation and user experience. Check out this resource to learn more: You can also find a helpful example here: . Once you have set up your routes, you can implement the following code:

var app = angular.module('myApp', [])
app.controller('DataController', function($scope, $http) {
    $http.get('https://example-api/data')
        .then(function(response) {
            $scope.data = response.data;
            $state.go('dashboard');
        }, function(error){
            console.log(error);
        });
});

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

javascript create smooth transitions when navigating between different pages

As a newcomer to JS, I am currently working on creating a website with an introduction animation. My goal is to have this animation displayed on a separate page and once it reaches the end, automatically redirect to the next webpage. <body onload="setT ...

Compare several objects or arrays based on a selected array and combine them into a single object containing all matching elements from the selected array

selection = ["A", "lv3", "large"] Data = [{ id:1, title:"this is test 1", category:"A, D", level:"lv5", size: " medium", }, id:2, title:"this is test 1", category:"C ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

Nuxt middleware's redirect function is causing the state to become null

My Nuxt app has a middleware issue where everything works fine except when the redirect function is used. When I comment out the line with redirect('/admin') it functions properly, even showing state data in the console log. But as soon as I unco ...

Tips for retrieving specific database entries using a JavaScript function

I'm currently in the process of developing a web directory that showcases organizations based on the selected county by utilizing an XML database. During testing, I have configured it to only display organization names and counties for now. However, ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...

Does it typically occur to experience a brief pause following the execution of .innerHTML = xmlhttp.responseText;?

Is it common to experience a brief delay after setting the innerHTML with xmlhttp.responseText? Approximately 1 second delay occurs after xmlhttp.readyState reaches 4. This issue is observed when using Firefox 3.0.10. ...

How can one authenticate an express session when sending a POST request?

Is there a way to verify that a user is sending a post request in order to prevent unauthorized posting to a URL? I am currently using express-session for this purpose, but I'm open to exploring alternative methods as well. I attempted to implement t ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Tips for concealing the Google Chrome status bar from appearing on a webpage

I have been intrigued by the rise of Progressive Web Apps (PWAs) and I am eager to dive into understanding them better. One common feature I have noticed in PWAs is the ability to hide the browser chrome, including the URL bar, back button, search fields, ...

Tips for passing the name of a success function as a parameter in an AJAX request

My challenge is to create an AJAX call as a single function, where I pass the success function name as a parameter. Here's the function that I attempted: function MakeApiCall(dataText, apiName, functionName) { $.ajax({ url: apiUrl + apiName, ...

"electron-builder - initially designated for building app for Mac only, but now configured to build for both Mac

This is my first attempt at creating an electronjs app, so I may not have a full grasp on what I'm doing. I've been following the instructions on GitHub and also this guide from Medium. Here's a snippet of my package.json: { (package.jso ...

Click event in dropdown selection options

Is it possible to use ng-click in select options for different functions to be triggered on each option selection? Other threads have suggested using the same controller function for all options, but I am looking to trigger different functions based on t ...

Assign a value to the <li> element and modify the prop when the user clicks using vue.js

I've been attempting to update props from child to parent using the $event in an @click event. I sent the data and $event from the parent to the child as shown below. in the parent component: <v-filter :sortTypePrice="sortTypePrice" :sort ...

My PayPal script (and all other JavaScript) was rendered dysfunctional by Onsen UI

I've been gradually incorporating Onsen UI into my existing web app. Currently, my home page file (index.jade) includes a splitter for navigation within the app. The splitter loads a NodeJS route that renders the requested page in jade. Everything wo ...

Invoking Ajax Within Every Loop

I am creating dynamic HTML buttons where, upon pressing each button, I want to make an AJAX call to retrieve a value. However, I am encountering an issue where I get as many console outputs as the number of buttons pressed. Here is my PHP code: if(isset($ ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...