用Node.js实现html5模式下的Angular路由



我知道有其他的答案,但他们似乎有警告。

这个会导致重定向,这对于使用Mixpanel的前端应用来说是致命的,并且双重加载Mixpanel会在浏览器中显示Maximum Call Stack Size Exceeded错误。

这个使用sendFile,我个人无法工作。试图诊断,我只是建议使用express.static()

目前我的代码是这样的:

home.js -一些路由,最后一个打算作为前端站点。

var indexPath = path.resolve( __dirname, '../' + process.env.PUBLIC_FOLDER )
router.get( '/:user/:stream/:slug', function( req, res, next ) {
    if ( req.headers['user-agent'].indexOf( 'facebook' ) != -1 ) {
        // stuff to handle the Facebook crawler
    } else return next()
})
router.get( '/*', function( req, res ) {
    express.static( indexPath )
})

server.js -配置node/express

app = express();
app 
    .use( morgan( 'dev' ) )
    .use(bodyParser.urlencoded( { limit: '50mb', extended: true } ) )
    .use( bodyParser.json( { limit: '50mb' } ) )
    .use( '/api', require('./routes/usersRoute.js') )
    .use( '/', require( './routes/home' ) )
    .on( 'error', function( error ){
       console.log( "Error: " + hostNames[i] + "n" + error.message )
       console.log( error.stack )
    })
http
    .createServer( app ).listen( process.env.PORT )
    .on( 'error', function( error ){
       console.log( "Error: " + hostNames[i] + "n" + error.message )
       console.log( error.stack )
    })

更多信息

你可以看到我试图使用express.static()的原因是因为当我使用res.sendfile()时,我得到一个像这样的问题,控制台说Unexpected token '<'。不幸的是,答案并没有具体说明解决问题的方法,提问者说他们解决了问题,但没有给出答案。

在我的尝试和错误中,我增加了一些表达,像这样

.use( '/app/app.js', express.static( indexPath + '/app/app.js' ) )
.use( '/app/views', express.static( indexPath + '/app/views' ) )
.use( '/app/controllers', express.static( indexPath + '/app/views' ) )
.use( '/app/directives', express.static( indexPath + '/app/views' ) )
.use( '/app/vendor', express.static( indexPath + '/app/vendor' ) )
.use( '/js', express.static( indexPath + '/js' ) )
.use( '/css', express.static( indexPath + '/css' ) )
.use( '/fonts', express.static( indexPath + '/fonts' ) )
.use( '/images', express.static( indexPath + '/images' ) )
.use( '/api', require('./routes/usersRoute.js') )
.all( '/*', require( './routes/home' ) )

在我的home.js路由文件中添加了这个

router.get( '/*', function ( req, res ) {
    res.status( 200 ).set( { 'content-type': 'text/html; charset=utf-8' } )
    .sendfile( indexPath + '/index.html' )
})

在浏览器中,我可以看到我所有的文件正在加载,但上面的<错误。当我进行刷新时,我看到这个/*/路由被调用了数百次,所以我认为.use( '...', ... )配置被忽略了。


下面是乔纳斯要求的另一个例子。

var indexPath = path.resolve( __dirname, process.env.PUBLIC_FOLDER )
mongoose.connect( process.env.MONGOLAB_URI )
app = express();
app 
    .use( morgan( 'dev' ) )
    .use(bodyParser.urlencoded( { limit: '50mb', extended: true } ) )
    .use( bodyParser.json( { limit: '50mb' } ) )
    .use( '/api', require('./routes/usersRoute.js') )
    .use( '/', require( './routes/home.js' ) )
    .use( express.static( indexPath ) )
    .on( 'error', function( error ){
       console.log( "Error: " + hostNames[i] + "n" + error.message )
       console.log( error.stack )
    })

我也做了同样的没有.use( '/', require( './routes/home.js' ) )行试图缩小任何问题,但它是相同的结果。如果URL中有#,则页面将加载,但浏览器将删除#(到目前为止还不错)。但如果我按刷新,或者手动输入URL,它会给出一个错误,如Cannot GET /home/splash,其中/home/splash是我要去的路径

您可能以错误的方式使用了快速中间件。查看文档告诉我,例如下面的代码

.use( '/images', express.static( indexPath + '/images' ) )

为文件夹indexPath + '/images'下的任何文件提供以下url:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/images/logo.png
http://localhost:3000/images/whatever.jpg

这是你期望它做的吗?

我的建议是从

.use( '/', require( './routes/home' ) )

.use(express.static( indexPath ))

因为根据文档,它将从根路径提供indexPath文件夹下的所有静态文件,即。没有前缀

我想这是目前为止我所能提供的所有帮助。如果这还不行,也许你可以分享一些小的代码示例,我可以用它来复制我自己的。

<标题> 更新

Ok。我试着创造一个简单的例子。我用下面的方法实现了它。我的目录结构是这样的:

|- index.js
|- public/
|---- index.html
|---- test.html
|---- main.js
|---- angular.js
|---- angular-route.js

index.js为节点服务器。注意路由的顺序。我还添加了一些/home/login的例子,以清楚地说明如何添加其他不应该通过angular的服务器路由。

var http = require('http');
var express = require('express');
var app = express();
app
    .use(express.static('public'))
    .get('/home/login', function (req, res) {
        console.log('Login request');
        res.status(200).send('Login from server.');
    })
    .all('/*', function ( req, res ) {
        console.log('All');
        res
            .status( 200 )
            .set( { 'content-type': 'text/html; charset=utf-8' } )
            .sendfile('public/index.html' );
    })
    .on( 'error', function( error ){
       console.log( "Error: n" + error.message );
       console.log( error.stack );
    });
http
    .createServer( app ).listen( 8080 )
    .on( 'error', function( error ){
       console.log( "Error: n" + error.message );
       console.log( error.stack );
    });
console.log('Serving app on port 8080');

index.html非常简单。

<!doctype html>
<html>
<head>
    <title>Angular HTML5 express test</title>
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="angular-route.js"></script>
    <script type="text/javascript" src="main.js">
    </script>
</head>
<body ng-app="app">
    <div ng-view></div>
</body>
</html>

main.html只是添加了一些内容。重要的是/test

链接
<div>
    <h1>This is just a {{val}}</h1>
    <button ng-click="clicked()">Click me!</button>
    <span>You clicked {{counter}} times</span>
    <a href="/test">test me!</a>
</div>

test.html实际上是不相关的

<div>
    <h4>What a beautiful day to test HTML5</h4>
</div>

main.js正在做核心的angular html5工作

angular.module('app', ['ngRoute'])
    .config(function($locationProvider) {
        $locationProvider
            .html5Mode({
                enabled: true, // set HTML5 mode
                requireBase: false // I removed this to keep it simple, but you can set your own base url
            });
    })
    .config(function($routeProvider) {
        $routeProvider
            .when('/test', {templateUrl: 'test.html', controller: function() {
                console.log('On /test.');
            }})
            .when('/', {templateUrl: 'main.html', controller: 'MyTestCtrl'})
            .otherwise('/');
    })
    .controller('MyTestCtrl', function ($scope) {
        self = $scope;
        self.val = 'TeSt';
        self.counter = 0;
        var self = self;
        self.clicked = function() {
            self.counter++;
        };
    });

代替:

router.get( '/*', function( req, res ) {
    express.static( indexPath )
})

router.get( '/:anyreq', function( req, res ) {
    express.static( indexPath )
})

看起来您的AJAX请求可能有问题。
我通常这样设置我的路由:

app.use(express.static(path.join(__dirname, "./public"))); app.use("/", require(path.join(__dirname, "./routes")));

,并在前端使用指令中的templateUrl: "/templates/home.html"

$http.get("/images").success(...).error(...)使用$http.

在templateUrl的情况下,应用程序将进入公共目录,然后路径模板,并提供html文件。在$http的例子中,我指定了一个路由,这样应用程序就会检查公共目录,而不会看到图像路径,然后移动到路由器。在路由器中,我有一个router.get("/images", function (req, res, next) { res.sendFile(...);res.send({(data)}) }),它将我需要的文件发送回前端,在那里它被成功处理程序捕获。

最新更新