所以我首先认为这是 Heroku 的问题,但是当使用 NodeJS 本地运行时也会发生同样的情况。
我的 Angular 应用程序的主页显示正常,并且在使用链接导航时路线可以正常工作。
但是,如果我尝试刷新路由上的页面(比方说/login),那么服务器仅使用以下文本进行响应:
Heroku 上的 /app/dist/meal-planner/index.html
,以及
/Users/name-here/Development/workspace/meal-planner/dist/meal-planner/index.html
本地
这是我的server.js:
//Install express server
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
// Serve only the static files form the dist directory
app.use(express.static(path.join(__dirname, '/dist/meal-planner')));
// For all GET requests, send back index.html (PathLocationStrategy)
app.get('*', (req,res) => {
res.send(path.join(__dirname, '/dist/meal-planner/index.html'));
});
// Start the app by listening on the default Heroku port
const port = process.env.PORT || 8080;
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log('Running on port ' + port));
还有我的folder structure以防万一...
最佳答案
res.send(path.join(__dirname, '/dist/meal-planner/index.html'));
path.join
返回一个字符串,您将该字符串作为响应发送。这解释了为什么服务器以文本响应。
您可能想要sendFile
而不是发送
:
res.sendFile(path.join(__dirname, '/dist/meal-planner/index.html'));
关于node.js - Angular 2+/NodeJS/Express : Routing fails on page refresh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51509360/