我使用的是https://github.com/shorttompkins/benm,我想在不使用散列的情况下实现pushState。我已经设置了:
Backbone.history.start({pushState: true});这是我的server.js:
var express = require('express'),
http = require('http'),
path = require('path'),
routes = require('./app/routes'),
exphbs = require('express-handlebars'),
mongoose = require('mongoose'),
seeder = require('./app/seeder'),
app = express(),
bodyParser = require('body-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');
app.engine('handlebars', exphbs({
defaultLayout: 'main',
layoutsDir: app.get('views') + '/layouts'
}));
app.set('view engine', 'handlebars');
app.use(morgan('dev'));
app.use(bodyParser());
app.use(methodOverride());
routes.initialize(app, new express.Router());
// static asset routes
app.use('/', express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(path.join(__dirname, 'bower_components')));
// development only
if ('development' === app.get('env')) {
app.use(errorHandler());
}
//connect to the db server:
mongoose.connect('mongodb://localhost/MyApp');
mongoose.connection.on('open', function() {
console.log('Connected to Mongoose.');
// check if the db is empty, if so seed it with some contacts:
seeder.check();
});
//routes list:
routes.initialize(app);
//finally boot up the server:
http.createServer(app).listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});和我的routes.js:
var home = require('../controllers/home'),
contacts = require('../controllers/contacts');
module.exports.initialize = function(app) {
app.get('/', home.index);
app.get('/api/contacts', contacts.index);
app.get('/api/contacts/:id', contacts.getById);
app.post('/api/contacts', contacts.add);
app.delete('/api/contacts/:id', contacts.delete);
};这工作得很好,直到我尝试刷新一个具有主干路由的页面。http://localhost:3300/add则找不到该路由,并且我得到一个错误'Cannot get /add‘。
根据我所读到的内容,我需要添加一个通用路由,如下所示:
app.get('*', function(req, res){
// serve home page
});但是我不知道如何使用快车把手来做到这一点。
我尝试过的一切似乎都阻止了正在提供的静态内容,即使我在server.js中获得了express.static路由
任何人的帮助都将不胜感激。
发布于 2015-05-11 13:59:32
当使用page状态时,浏览器不会请求通过pushState()添加的网址,但在重新加载页面或在该位置重新启动用户代理时可能会这样做。
来自Mozilla开发者网络:
这适用于所有用户代理。
that state的思想是,在不请求文档的情况下存储URL的状态对象。但是,在前一个浏览会话被破坏后,当请求用户代理加载该URL时,服务器需要能够提供该URL。请注意,用户也可能将URL加入书签或通过电子邮件发送给另一个人。
您的服务器和客户端应该能够根据该URL初始化应用程序状态。
既然你说了,你
更喜欢使用标准的URL,并保留散列,以便深入查看选项卡、ids等内容。
你最好的选择似乎是在你的后端实现路由。在你的前端“生成”的所有路由都应该被服务。您的单页应用程序文档需要用于这些URL中的任何一个。
如果您的应用程序应该在正确的点进行初始化/启动,则需要
上启动应用程序的URL的状态。
给定当前路由/contacts/24552,
对于选项1:例如,您可以处理路由,收集24552的联系人数据,并使用内联的联系人数据提供单页应用程序文档。
对于选项2:您可以为任何路由( API路由除外)提供单页应用程序文档,检查URL客户端并执行请求客户端。例如,您可以解析location.pathname,提取相关信息(例如“联系人”和ID),然后直接调用路由处理程序,或者导航到未处理的路由并返回到路由/contacts/24552以触发路由处理程序。
注意:在您的内容中使用锚点时,您也可以使用基于散列的URL。您可以生成这些锚点名称(ID),并为它们添加当前应用程序状态路由的前缀。您的主干路由处理程序必须忽略这些锚点名称。
https://stackoverflow.com/questions/30088425
复制相似问题