带有快速的angular度HTML5模式

我知道这个问题有答案,但他们并没有完全为我工作。 我正在使用Angular 1.4和Express 4. Express正在处理API调用,Angular应该处理所有的HTML。

我的快递app.js:

var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); require('./routes/api')(app); var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../client'))); // This covers serving up the index page app.use(express.static(path.join(__dirname, '../client/.tmp'))); app.use(express.static(path.join(__dirname, '../client/app'))); app.all('*', function(req, res) { res.redirect('/index.html'); }); module.exports = app; 

这里是angular度app.js

 angular .module('punyioApp', [ 'ngAnimate', 'ngAria', 'ngCookies', 'ngMessages', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ]) .config(function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main' }) .when('/howitworks', { templateUrl: 'views/howitworks.html', controller: 'HowItWorksCtrl', controllerAs: 'howitworks' }) .otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }); 

现在,如果我去http:// localhost:3000 / ,我得到了主要的Angular视图,如预期的那样。 问题是当我去http:// localhost:3000 / howitworks ,它将我redirect到http:// localhost:3000 / index.html并且不显示'howitworks'视图。 如何修复快速路由器,以便我可以去http:// localhost:3000 / howitworks ?

你的代码只是将每个请求redirect到index.html ,这不是你想要的。 您确实需要该文件,但是由于Angular处理路由,您只需要Express发送文件,而不会询问任何问题。

基本上,你不应该使用redirect ,但sendFile

 app.get('/*', function(req, res) { res.sendFile(__dirname + '/index.html') }); 

另外,正如有人在评论中指出的,你应该使用get而不是all

如果你使用的是angularjs ui-router,不需要使用express,你可以使用node-static或者nginx,使用grunt或者gulp connect插件来配音,我认为这样更好。

在玉的情况下,你可以使用:

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