简体   繁体   中英

Using both Angular routeProvider and Express routes

I'm trying to make angular's routeProvider to manage all the routes of my app. I define my routes accordingly in the app.js file of angular (client side):

(function(){

var app = angular.module("Crowdsourcing", ["ngRoute"]);

app.config(function($routeProvider){
    $routeProvider
        .when("/single/:street/:buildingNumber/:apartmentNumber", {
            templateUrl: "/views/single.html'",
            controller: "ListingCtrl"
        })
        .otherwise({redirectTo:"/"});
});
}());

However, when writing a URL (eg /single) on the browser that request is tried to be handled by my backend express/node api. Thus, it is not found because the backend routes are for example /api/foo. How can I make sure Angular's routeProvider always manages my requests?

And more important what is the basic flow of the application? When Client writing a URL how does the application knows whether the url is handled by express js or by routeProvider ?

Generally you distinguish URLs which are handled by the angular app from the express URLs by using a # sign between hostname and page URL.

For example:

If you want to request an URL from the backend you would call: http://host.com/api/foo/

Instead if you want to request an URL from the angular app you would call: http://host.com/#/single

So if you want to call the angular app URL you have add the # sign.

This is a very important fact you need to keep in mind when working with single page applications.

Update:

Have a look at this seed project: https://github.com/btford/angular-express-seed

It uses the a similar technology stack as your project. This should make it more clear for you.

I have faced the same issue few days ago. The problem is, even when you make a server call for data it redirects it to client side routing and searches in $routeProvider .

You need to make sure you add something like below code in your server.js . It means when ever there is a call starting with /api then it will redirect it to the routes in server side instead of client side routing.

var api = express.Router();
require('./app/routes')(api);
app.use('/api', api);

In your factory when we make a call as below this will go to server side routes.js rather than client side.

$resource('/api/adduser')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM