node.js - Angular 2+/NodeJS/Express : Routing fails on page refresh

标签 node.js angular express heroku routes

所以我首先认为这是 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/

相关文章:

javascript - 使用 Node.js 发送 Json 时为 "Maximum call stack size exceeded"

css - 样式 css 文件未应用于我的网站,因为我猜是因为新的 Windows 更新

javascript - 如何使用 NPM 镜像

angular - 单击添加按钮将行添加到表中,新行是每个单元格中的表单字段

node.js - Express Mongoose 查询无法设置标题

node.js - Google Cloud App Engine 上的 Nodejs 应用无法启动

Angular 6 : Passing Observable response to another Observable

angular - 如何在 vscode 中使用一个(或两个)快捷方式在 TypeScript 和 HTML 之间切换?

node.js - Heroku 构建在 package.json 文件中找不到 `@types`

javascript - Passport.js req.user 返回 : 'Promise { false }' - How do I get the current sessions' username?