使用 express.js 提供聚合物应用路由页面?

Serving polymer app-routed pages with express.js?

我有一堆基于 Polymer 入门工具包的页面,可以很好地与 polymer serve 配合使用。但是,我需要通过服务器发送一些 ajax 请求进行数据库查询,所以我不得不用 express.js 编写自己的服务器代码。我的问题是,每当我进入非根页面并刷新时,我都会收到消息 Cannot GET /bugs 或任何 /page 名称。我的 index.html 页面正常引用 container.html,其应用程序路由代码如下:

<app-location route="{{route}}"></app-location>
    <app-route
        route="{{route}}"
        pattern="/:page"
        data="{{routeData}}"
        tail="{{subroute}}"></app-route>

...

<app-drawer id="drawer">
        <app-toolbar>Menu</app-toolbar>
        <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
          <a name="view-1" href="/view-1">View One</a>
          <a name="bugs" href="/bugs">Bugs</a>
        </iron-selector>
      </app-drawer>

...

<iron-pages
            selected="[[page]]"
            attr-for-selected="name"
            fallback-selection="view-404"
            role="main">
          <view-1 name="view-1"></view-1>
          <bugs-view name="bugs"></bugs-view>
        </iron-pages>

换句话说,它与默认的 Polymer 初学者工具包几乎完全相同。我的服务器代码如下:

var express = require('express');
var path = require('path');
var mysql = require('mysql');

var connection = mysql.createConnection({
    host     : 'host',
    user     : user,
    password : password,
    database : 'db'
});
connection.connect();
var app = express();

app.get('/sql', function(req,res) {
    //console.log(req.query.query);
    connection.query(req.query.query, function(error, results, fields) {
        if (error) {console.log(error); throw error;}
        else {
            res.send(results);
        }
    }.bind(this));
});

app.use(express.static(__dirname));
app.use(express.static(__dirname+'/src'));
app.listen(8080);

console.log("Server listening on localhost:8080");

我可以很好地加载 localhost:8080,并且可以很好地导航到页面,但是每当我尝试在任何页面上刷新但 root 时,它都会给我 Cannot GET /page 错误。这使开发成为一种非常令人沮丧的体验...

尝试将此添加到您的服务器配置中:

app.get('*', function(req, res) {
    res.sendfile('./public/index.html', {root: '.'}); 
});

而不是 ./public/index.html,输入您的 index.html

的路径

将此放在所有其他路由之后,这样它就不会覆盖 them.This 方式,无论您重新加载哪个页面,您的服务器仍将发送您的 "starting point",这当然会拉入所有 javascript 和 css。在所有这些之后,一旦 angular 启动,它的路由器就会接管并将你带到你应该去的地方。