重定向到Node.js中的UI路由器状态

时间:2016-05-17 03:12:29

标签: angularjs node.js express angular-ui-router

我显示产品清单;单击产品行后,将显示全屏详细信息视图。我正在使用ui-router进行前端路由,以便从列表视图到详细视图。地址网址示例:http://localhost:3000/detail/product1

如果我将此网址输入浏览器地址,则不会重定向到该产品详细信息,而是会尝试加载index.html,因为它是nodejs中的默认网页。如何在node.js中重定向到ui-router状态?

Angular App.js

'use strict';

/* App Module */

var myApp = angular.module("myApp", ['ui.router']);

myApp.config(['$stateProvider', '$urlRouterProvider','$locationProvider',
           function($stateProvider, $urlRouterProvider,$locationProvider) {


$urlRouterProvider.otherwise('/');

$stateProvider

.state('/', {
    url: '/',
    templateUrl: 'partials/listView.html'
})

    .state('list', {
        url: '/',
        templateUrl: 'partials/listView.html'
    })
    .state('detail', {
        url: '/detail/:key',
        params: {
             key: { value: "" }
        },
        templateUrl: 'partials/detailView.html',
        controller: 'DetailController'
    })

// use the HTML5 History API
$locationProvider.html5Mode(true); 
}]);

nodeJS app.js:

    var express = require('express')
    , routes = require('./routes')
    , http = require('http')
    , path = require('path')
    , bodyParser = require("body-parser");

    var app = express();

    app.set('port', process.env.PORT || 80);

    //front end views are in /public folder; using html for views
    app.set('views', __dirname + '/public');
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');

    app.use(bodyParser.json());
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
    //parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true })); 


    //using index.html as starting point
    app.use(express.static(path.join(__dirname, '/public')));
    app.use(express.logger('dev'));

    app.use(express.methodOverride());
    app.use(app.router);


    //development only
    if ('development' == app.get('env')) {
       app.use(express.errorHandler());
    }

    app.get('/', routes.index); //redirect to index.html on page load
    app.get('/detail/*', function(req, res){

    var urlSegments = req.url.split('/',3);
    var key=urlSegments[2]; // product id 


    // ??? How can I redirect to detail state in angular ui-router here passing the key of the product ???
     });



app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

http.createServer(app).listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

谢谢

1 个答案:

答案 0 :(得分:0)

当状态更改为在url中使用查询时,问题已解决:

.state('detail', {
   url: '/detail?key',
   params: {
     key: { value: "" }
   },
   templateUrl: 'partials/detailView.html',
   controller: 'DetailController'
})