Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this:

index.ejs

<!DOCTYPE html>
<html>
<head>
  <title>Redirect Example</title>
</head>
<body>
  <p>INDEX PAGE</p>
  <form action="/redirect" method="post">
    <button type="submit">CLICK</button>
  </form>
</body>
</html>

test.ejs

<!DOCTYPE html>
<html>
<head>
  <title>Redirect Example</title>
</head>
<body>
  <p>YAY REDIRECTED</p>
</body>
</html>

app.js

var fs = require('fs');
var https = require('https');

var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

var app = express();
app.set('view engine', 'ejs');

app.get('/', function(req, res) {
  res.render('index');
});

app.post('/redirect', function(req, res){
  res.redirect('/test');
});

app.get('/test', function(req, res) {
  res.render('test');
});

var port = process.env.PORT || 1337;
app.listen(port, function(){
  console.log('http://localhost:' + port + '/');
});

This method automatically redirects the page to the "test" route since it uses a form to handle the post request.

However, when I try an angular approach, the automatic redirection doesn't work. How can I achieve this?

index.ejs

<!DOCTYPE html>
<html ng-app="project">
<head>
  <title>Redirect Example</title>
  <script src="/javascripts/jquery/jquery.js"></script>
  <script src="/javascripts/angular/angular.js"></script>
  <script src="/javascripts/angular/angular-route.js"></script>
  <script src="/javascripts/main.js"></script>
</head>
<body ng-controller="MainController">
    <button type="submit" ng-click="submit()">CLICK</button>
</body>
</html>

main.js

var app = angular.module('project', []);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {

  $scope.submit = function() {
    $http.post('/redirect');
  }
}]);

Answer №1

To ensure smooth redirection within your Angular application, it is recommended to handle it from within Angular itself as it is designed to operate on the client-side independently. One way to achieve this is by sending a status code from the server to instruct the client to redirect.

For instance, you can modify your express endpoint like so:

app.post('/redirect', function(req, res){
    res.status(300).send({ redirect:"/test"});
});

And adjust your Angular Controller as follows:

var app = angular.module('project', []);
app.controller('MainController', ['$scope', '$http', '$window', function ($scope, $http, $window) {

  $scope.submit = function() {
    $http.post('/redirect').then(function(data, status){
      $window.location.href = data.redirect; 
    });
  }
}]);

This approach allows you to define the redirection path directly in the server-side code.

Note: Additionally, remember to include a hashtag for your redirect in Angular unless HTML5 mode is enabled.

Answer №2

Node.js server creates genuine routes, while AngularJS routing relies on hash (#) tags such as -

Examples of routes in node.js -

app.get('/myroute') will appear as - http://localhost:8000/myroute

Demonstration of routes in AngularJS -

'/myangroute' will look like - http://localhost:8000/#/myangroute

In relation to your query, the code $http.post('/redirect'); does not perform a redirection but sends data to the '/redirect' route (which is defined on the server end). For redirection purposes, utilize the angularjs $location service.

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 a stunning horizontal bar chart with the react-d3-components framework

I am currently implementing a D3 chart using the react-d3-components library. So far, I have successfully generated a vertical bar chart. However, my specific requirement is to create a horizontal bar chart. import React from 'react'; import Reac ...

Setting isolated scope parameters can be done in a variety of ways

Here is the directive definition I have created: myApp.directive('myCategory', [function () { return { restrict: 'E', scope: { category: '=someCategory', }, templateUrl: 'category.html', ...

Leveraging ng-click and ng-hide/show directives within ng-repeat in Angular

I have a simple Single Page Website built with Angular. I utilized ng-repeat to generate content on the main page, where each item is an image. I am looking to create an alternate view for each image to display more details. I have implemented this feature ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

Enhance your viewing experience with the Zoom feature that activates when

I recently noticed on that I am able to zoom/enlarge a photo by clicking on it. Is there a way for me to incorporate this feature without purchasing the entire theme? While I understand the theme is designed for purchase, I only need this specific functi ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error ...

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

Using Express and React with Socket.io

I am currently working on setting up a basic WebSocket connection using Socket.io, Express, and ReactJS. Below is the code for the server: const express = require('express'); const socket = require('socket.io'); const path = require(& ...

The download attribute is not functioning properly on both Chrome and Edge browsers

I've been trying to use the download attribute, but it doesn't seem to be working. I have also attempted to use the target attribute to see if there are any issues with downloading from the server or from a web (https) source. Unfortunately, noth ...

Utilizing PHP for XML exportation and fetching it through AJAX to integrate it into the DOM, unfortunately, the XML content remains invisible

I've encountered a strange issue with a PHP script that generates valid XML output. I'm trying to fetch this data using an Ajax XMLHttpRequest call in the browser. Although Firebug confirms that the Ajax request is successful and the XML is vali ...

Automatically adding routes in ExpressJS: A seamless integration guide

If you've ever wanted to add specific prefixes to routes, like /before, and remove them at a certain point in your server.js file, here's an example of how you could achieve that: Check out this code snippet for reference: const express = requi ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Utilize Expo Auth Session to acquire Spotify's refresh token

Currently, I am attempting to implement Spotify login using the expo-auth-session in my Expo app. I have referred to the documentation provided by expo-auth-session which can be found at From what I gathered, the auth code flow returns an authorization co ...

Is it recommended to place the styles created by material-ui for child components after the styles generated for the parent component?

Utilizing material-ui, which utilizes JSS for styling a website. I have a component named Layout that applies margin to all its children (using the all children selector & > * in its style). This functionality works, but I would also like the child ...

Creating a new session in Node.js for every request

Our team is currently developing a nodejs application that requires the maintenance of sessions. We have implemented express to handle node variables, but we are facing an issue where a new session is created every time we hit a new service. The structure ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...