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

The cascade option in TypeORM entities

In my project, I am working with two entities named Order and Address, which are connected through a @ManyToMany relationship. For the Address entity: @ManyToMany(() => Order, (order) => order.address, { cascade: true }) @JoinTable() order: Order; ...

What steps can be taken to create an electron menu for easily conducting a general search within the current window?

I am searching for a solution to create an electron menu that includes the label "Find..." and performs a general search within the current browser window. While I was successful in adding the option, I am struggling to figure out how to access the browser ...

Securing Users with ReactJS and Loopback for Authentication

I am currently working on a small project and attempting to implement user authentication for the front end using ReactJS with Loopback. I have created a login view for users where they can sign up and log in successfully. However, my goal is to restrict a ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

Obtain the current date using Moment JS in JavaScript

Here is a scenario with code : let currentTime = moment(); console.log(currentTime.format()); // 2019-11-25T20:23:50+02:00 console.log(currentTime.toDate()); // 2019-11-25T18:23:50.916Z After applying the timezone change on Heroku using the command ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

What is the process for using jQuery to systematically alter the src attribute of all avatar images on Twitter.com?

Summary: I am learning JavaScript and jQuery, and wanted to write a script to replace "_normal.png" with ".png" for all "img.avatar" images on Twitter.com. I encountered an error which I will explain below. Background: Practice makes perfect, so I like to ...

What is the best way to retrieve the value from a PHP request?

I am encountering an issue with a multiselect form field named properties[]. When I attempt to retrieve the values in my controller using dd($request->get('properties')), it gives me ["1,2"]. However, trying to access the first ele ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Error message: Upon refreshing the page, the React Router is unable to read properties of

While developing a recipe application using the Edamam recipe API, everything was functioning smoothly until an issue arose when refreshing the Recipe Detail page. The error occurs specifically when trying to refresh the page with a URL like http://localho ...

Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version. TypeScript is the language ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

What is the process for generating a submatch for this specific expression?

Trying to extract account status information using a regular expression in the DOM. Here is the specific string from the page: <h3>Status</h3><p>Completed</p> Current regular expression being used: <h3>Status</h3>[&bs ...

Using NextJS to pass a string from an input field to getStaticProps via context

I am a beginner in NextJS and React, so please forgive my lack of knowledge. I am trying to figure out how to pass the text input by users from an input field (inside Header) to the getStaticProps function of a specific page using the React context API. I ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

How about using jQuery to display information alerts instead of the traditional alert function

Is there a way to display an alert within the login page itself if the login fails, instead of using a popup? error: function(data, status, xhr) { alert("Login failed."); } ...

VUEJS - Link the output from my function to my sub-template

I am looking for a way to link the output of my function with the child template. methods object methods: { filterOptions(checkedValues: any) { let filtered = this.cards.filter(card => { return card.profile .map(prof ...

What are the steps to implementing partial page functionality with the $http service in Angular?

Could someone assist me with executing an operation once a partial page has been successfully loaded using the $http service in Angular? The operation involves checking a checkbox based on the scope value. I have included the source code below: Here i ...

Establishing connectivity between an AngularJS application and Mongodb by utilizing NodeJS

I have implemented an AngularJS application that successfully retrieves data from an array in a controller using ng-repeat. Now, my goal is to integrate it with Mongodb through NodeJS so that the app can fetch data from a Mongodb collection. Additionally, ...