1
votes

I have a bunch of pages based off of the Polymer starter kit, which work fine with polymer serve. However, I need to send some ajax requests through a server for database querying, so I was forced to write my own server code with express.js. My issue is that whenever I enter a page that isn't root and refresh, I get the message Cannot GET /bugs or whatever the /page name is. My index.html page references a container.html as normal, which has app-route code as follows:

<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>

In other words, it's almost exactly the same as in the default Polymer starter kit. My server code is as follows:

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");

I can load localhost:8080 fine, and navigate to pages just fine, but whenever I try to refresh on any page but root it gives me the Cannot GET /page error. This has made development an intensely frustrating experience...

1

1 Answers

2
votes

Try adding this to your server config:

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

Instead of ./public/index.html, put the path for your index.html

Put this AFTER all of your other routes so it does not override them.This way, no matter the page you reload on, your server will still send your "starting point", which will then of course pull in all of your javascript and css. After all of that, once angular bootstraps, it's router will take over and take you where you should be.