Express and URL rewriting | HTML5 history

冷暖自知 提交于 2020-01-11 03:40:05

问题


I'm trying to build a simple server to serve a single HTML page where all the logics are handled by Angular. As far as I'm using the HTML5 history mode I'm able to navigate through standard URLs.

Now, to make this work I need to enable URL rewriting. I tried with this bunch of lines and although return always the correct HTML page, the URL vary and does not keep the initial value. For example /popular should load index.html and leave the URL /popular so that the JS logic can load the desired page.

Here follows the express code.

var express = require("express");
var app = express();

app.configure(function(){
  app.use(express.static(__dirname + '/dist'));
}); 

app.get("/*", function(req, res, next){
  res.sendfile(__dirname + '/dist/index.html');
});

app.listen(3000);

Any suggestion is appreciated. Thanks everyone.


回答1:


You need to set the root directory for relative filenames.

app.all('/*', function(req, res) {
  res.sendfile('index.html', { root: __dirname+'/dist' });
});


来源:https://stackoverflow.com/questions/15987451/express-and-url-rewriting-html5-history

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!