【问题标题】:Express routing for single page app doesn't seem to work单页应用程序的快速路由似乎不起作用
【发布时间】:2016-11-07 17:50:49
【问题描述】:

我有一个简单的 server.js 文件如下:

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

app.set('port', (process.env.PORT || 3031));

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('build'));
  app.get('*', (req, res) => {
    res.sendFile('build/index.html');
  })
}

app.listen(app.get('port'), (error) => {
  if (error) return console.error(error.message);
  console.log(`Server started at: http://localhost:${app.get('port')}/`);
})

我希望它在生产中将所有路径重新路由到 index.html 并启动服务器。目前路由位似乎不起作用,因为我收到以下错误:

服务器开始于:http://localhost:3031/ TypeError: path must be 绝对或指定根到 res.sendFile

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

尝试将根目录添加到路径

res.sendFile(__dirname + '/build/index.html');

【讨论】:

    【解决方案2】:

    res.sendFile 需要绝对路径,正如错误所说。

    尝试使用__dirname global:

    res.sendFile(__dirname + 'build/index.html');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-12
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      相关资源
      最近更新 更多