【问题标题】:Angular 2+/NodeJS/Express: Routing fails on page refreshAngular 2+/NodeJS/Express:页面刷新时路由失败
【发布时间】:2019-01-01 17:02:24
【问题描述】:

所以我首先认为这是 Heroku 的问题,但是在使用 NodeJS 在本地运行时也会发生同样的情况。

我的 Angular 应用程序的主页显示正常,使用链接导航时路由正常工作。

但是,如果我尝试刷新路由上的页面(比如说 /login),那么服务器只会响应以下文本: /app/dist/meal-planner/index.html 在 Heroku 上,以及 /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,以防万一……

【问题讨论】:

    标签: node.js angular express heroku routing


    【解决方案1】:
    res.send(path.join(__dirname, '/dist/meal-planner/index.html'));
    

    path.join 返回一个字符串,您将该字符串作为响应发送。这解释了为什么服务器以文本响应。

    您可能想要sendFile 而不是send

    res.sendFile(path.join(__dirname, '/dist/meal-planner/index.html'));
    

    【讨论】:

      猜你喜欢
      • 2017-10-06
      • 1970-01-01
      • 2017-02-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多