我已经配置了这样的ui-router:
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: "/home",
templateUrl : 'home/home.html',
controllerUrl: 'home/controller.js'
})
.state('blog', {
url: "/blog",
templateUrl : 'blogger/blog.html',
controllerUrl: 'bloger/controller.js'
})
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
});
服务器代码:
var express = require('express');
var serveStatic = require('serve-static');
var server_port = 9000;
var server_ip_address = '127.0.0.1'
var app = express();
app.use(express.static('app'));
app.use(serveStatic('app', {'index': ['index.html', 'index.htm']}));
dirName = 'app';
options = {
root: dirName,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
app.get('*', function(req, res) {
return res.sendFile('index.html', options);
});
app.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + server_port)
});
但每当我按下Ctrl / Command + R(或刷新)时,它会说它无法找到路径?我怎样才能解决这个问题呢?
文件夹结构:视图:./ app / home / ,app / blog / 基本文件: ./app/index.html Angular UI-routing from:./ app / base.js
答案 0 :(得分:1)
问题出在服务器设置中。 Angular是Front Controller应用程序。您需要将每个请求重定向到服务器上的index.html / index.php。例如,apache中的Htaccess设置。有关详细信息,请访问:htaccess redirect for Angular routes
答案 1 :(得分:0)
您可以在app.js中使用以下代码,&然后它工作:
更新:
/** Below code set the html as your default engine*/
var fs = require('fs');
app.engine('html',function(path,opt,fn){ //manishp
fs.readFile(path,'utf-8',function(err,str){
if(err) return str;
return fn(null,str);
});
});
app.get('*',function(req,res){
res.render('<your_layout_file_or_basefile>');
});
这主要是因为你的AngularJS路线不是真正的html页面。例如,如果您在角度应用程序中有/ login的路由。如果您从应用程序内部链接到此URL,此URL将正常工作,但如果用户尝试直接转到该页面,则服务器将返回404。
这是因为AngularJS HTML5模式使用History API将新网址推送到您的浏览器。是的,这需要在服务器端进行一些额外的工作,以使这些URL返回正确的内容。
答案 2 :(得分:0)
问题来自您的服务器端,您应该处理server.js
文件中的所有路由。
例如,这里是片段
router = settings.express.Router()
dirName = settings.path.resolve(__dirname, '..', '..');
options = {
root: dirName + '/website/views',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
router.get('*', function(req, res) {
return res.sendFile('index.html', options);
});