[英]Nodejs express render not working with ejs
我在節點服務器上使用express ejs在多視圖應用程序中呈現視圖。 在客戶端,我正在使用Angularjs。 初始視圖是一個登錄頁面,在使用res.render('pages/login')
時會正確顯示。 我希望在用戶成功連接時呈現新視圖,但對於下一個res.render('pages/home')
,它會保留在登錄頁面上,盡管我在客戶端收到正確的HTML。 這是我的相關代碼:
部分文件結構:
App
public/js/Script.js
views/pages
login.ejs
home.ejs
server.js
server.js
...
app.get('/',function(req, res){
res.render('pages/login'); //being displayed
});
app.get('/rest/home',function(req, res){
res.render('pages/home'); //not being displayed
});
app.post('/login',function(req, res){
//authentification
});
...
的script.js
.controller ('loginController', function ($scope, $http) {
$scope.authent = function(){
$http({
method: 'POST',
url: '/login',
data: $.param($scope.loginData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(res){
$scope.launch();
});
$scope.launch = function(){
$http({
method: 'GET',
url: '/rest/home',
}).success(function(res){
alert(res); //Here, I am getting the content of home.ejs, but the view doesn't load in browser
});
};
})
.controller ('homeController', function () {
});
login.ejs
<html ng-app="App">
<head>
...
</head>
<body ng-controller="loginController">
<div id="loginView">
<form name="login" id="login" ng-submit="authent()">
<input id="login_id" name="login_id" type="text" ng-model="loginData.loginId"/>
<input id="password" name="password" type="password" ng-model="loginData.password"/>
<input type="submit" class="submit" value="Login"/>
</form>
</div>
</body>
</html>
home.ejs
<html ng-app="App">
<head>
...
</head>
<body ng-controller="homeController">
<h1>Home</h1>
</body>
</html>
這是我第一次使用帶角度的ejs而且我不太確定我的方法,因此對於更好的方法的任何建議也受到歡迎。 我嘗試過使用Route,但不是很滿意。 我希望我的解釋清楚。
最后我使用了$routeProvider
。 這是解決方案:
文件結構:
App
/public/js/Script.js
/views/
layout.ejs
/partials/
login.ejs
home.ejs
/routes/
index.js
server.js
server.js
...
var engine = require('ejs-locals');
var routes = require('./routes');
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.get('/partials/:name', routes.partials);
app.get('/', routes.index); //Important to place this last
...
index.js
exports.index = function(req, res){
res.render('layout');
};
exports.partials = function (req, res) {
var name = req.params.name;
res.render('partials/' + name);
};
的script.js
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'partials/login',
controller : 'loginController'
})
.when('/home', {
templateUrl : 'partials/home',
controller : 'homeController'
})
.otherwise({redirectTo: "/"});
})
app.controller ('loginController', function ($scope, $http) {
...
$scope.launch = function(){
$http({
...
}).success(function(res){
$location.path('/home');
});
};
})
layout.ejs
...
<body>
...
<div ng-view></div> <!-- This section will be replaced with rendered view -->
...
</body>
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.