AngularJS: Relative link paths are broken when html5mode(true) is on

可紊 提交于 2019-12-04 08:10:44

Thanks to @trehyu for helping me get to this answer.

Like he wrote, I needed something setup on my server.js file that redirects the user to my "index.html" file.

So depending on your file structure...

BEFORE (not working)

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

app.use(express.static(__dirname + '/front'));
var port = process.env.PORT || 8000;
app.listen(port);

AFTER (working)

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

app.use('/js', express.static(__dirname + '/front/js'));
app.use('/build', express.static(__dirname + '/../build'));
app.use('/css', express.static(__dirname + '/front/css'));
app.use('/images', express.static(__dirname + '/front/images'));
app.use('/pages', express.static(__dirname + '/front/pages'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('/front/index.html', { root: __dirname });
});

var port = process.env.PORT || 8000;
app.listen(port);

I hope this helps someone else!

When HTML5mode is set to true, you need something setup on your server that automatically redirects the user to your index page, so that the AngularJS UI Router can take over from there.

The reason for this is that without the hash (#) in the URL, it takes it as a literal URL and tries to navigate there when you refresh or paste the url directly.

I'm not very familiar with Node so not sure how you would do that, but there is a FAQ page on the UI Router GitHub that should help you get started: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

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