Express 4, NodeJS, AngularJS routing

前端 未结 1 1721
滥情空心
滥情空心 2020-12-21 01:09

I am using Express 4 to host my AngularJS app on my backend, with Nginx as my frontend server. However html5 mode does not seem to work, as I will get a Cannot /GET error wh

相关标签:
1条回答
  • 2020-12-21 01:38

    I'm assuming you are using a "single page" angular app, so one html page that uses ng-view to load all the other partials.

    In this case you need to do something like this:

    Express 4:

    var express = require('express'),
        app = express(),
        server = require('http').Server(app),
        bodyParser = require('body-parser'),
        db = require('./db'),
        io = require('./sockets').listen(server),
        apiRoutes = require('./routes/api'),
        webRoutes = require('./routes/web');
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
      extended: true
    }));
    app.use('/api', apiRoutes);
    app.use(express.static(__dirname + '/public'));
    // Here's the new code:
    app.use('/*', function(req, res){
      res.sendfile(__dirname + '/public/index.html');
    });
    
    server.listen(3000, function() {
      console.log('Listening on port %d', server.address().port);
    });
    

    The problem you're facing is that even though you have routes setup for '/login' before the routes are fired they need to be loaded. So the server tries to find a match for the route '/login' which it can't returning the 404. In the case of single page angular apps all the routes you use in routing must be caught by a route, app.get('/*', ... in this case, and then return the main angular.js html page. Note that this is the last call so it will be evaluated last, if you put it first it will prevent all the subsequent rules from running as express just runs the handler for the first rule it encounters.

    0 讨论(0)
提交回复
热议问题