使用pushState为Backbone SPA配置节点Express [英] Configure node express for Backbone SPA with pushState

查看:60
本文介绍了使用pushState为Backbone SPA配置节点Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Express应用程序有一个休息服务器和一个使用Backbone的SPA.使用#历史记录,所有工作正常,即

My express app has a rest server and a SPA using Backbone. All works fine using # history, i.e.

Backbone.history.start();

如果我这样做:

Backbone.history.start({ pushState: true });

Backbone路由器停止工作-Backbone处理得很好的路由(例如#route)在变为/route时被发送到Express.表达错误:

the Backbone router ceases to work - a route that Backbone handles fine (e.g. #route) gets sent to Express when it becomes /route. Express errors with:

Cannot GET /route

我尝试过:

Backbone.history.start({ pushState: true, root '/' });

但没有区别.

我也尝试过:

app.use('/*', function ...

在Express中-没有区别.

in Express - no difference.

表达server.js:

express server.js:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.render('index.ejs');
});

var rest = require('./routes/rest');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/rest', rest);

app.listen(3000);

骨干路由器(瘦了一点):

The Backbone router (slimmed a bit):

const Router = Backbone.Router.extend({
  routes: {
    '': Controllers.home,
    'admin(/:table)(/:id)': Controllers.admin,
    'master(/:table)(/:id)': Controllers.master
  }
});
Backbone.history.start({ pushState: true });

我不需要任何SEO,我只是想在应用程序的路线中拍摄那些#".

I don't need any SEO, I'd just like to get shot of those '#' in the app's routes.

推荐答案

我认为路由器工作正常.当您直接从浏览器而不是应用程序中调用/index.html/someroute时,它不起作用".

I think the router is working fine. It's "not working" when you are calling directly /index.html/someroute from the browser instead of the app.

要处理此问题,您必须以快递方式抓住它

To handle this you have to catch it in express

app.get('*', function...)

应该工作.

请务必先声明另一条路线(例如/rest),否则在到达'/rest'之前将被'*'捕获.这是由于express所使用的中间件模式(提醒您,您可能已经知道这一点).

Be sure to declare the other route first (like /rest) otherwise it will be caught by '*' before reaching '/rest'. This is due to the middleware pattern express is using (just a reminder you may already know this).

希望有帮助!

这篇关于使用pushState为Backbone SPA配置节点Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆