【问题标题】:Express app.get('*') does not apply to '/'Express app.get('*') 不适用于 '/'
【发布时间】:2017-01-23 20:57:09
【问题描述】:

我有一个简单的快速服务器文件。

我正在尝试让我的 app.get('*') 块中的任何代码执行。但是,当我放入 console.log 时,它不会显示在我的根目录中。它适用于我的其他路线,但绝不适用于“/”路线。作为参考,我正在本地开发,所以它不适用于http://localhost:8080/

const app = express();

const port = process.env.PORT ? process.env.PORT : 8181;
const dist = path.join(__dirname, 'dist');

app.get('*', (req, res, next) => {
  console.log('Why wont you show on /')
});
app.use(express.static(dist));

//These two routes work...
app.get('/info', getInfo);
app.get('/infoDetail', getID);

app.listen(port, (error) => {
    if (error) {
    console.log(error); // eslint-disable-line no-console
}
  console.info('Express is listening on port %s.', port); // eslint-disable-line no-console
});

dist文件夹已经编译好css、js和index.html

【问题讨论】:

  • 使用app.all('*', (req, res, next) => {是否有效?

标签: express


【解决方案1】:

我刚刚创建了一个简单的测试快递应用:

const express = require("express");

let app = express();

app.get('*', (req, res, next) => {
  res.json({ hi: 'there' });
});

app.listen(3000);

当我运行这个示例并点击 / url 时,我确实得到了所需的 JSON 响应。

您确定您的示例是您正在运行的确切代码吗?

【讨论】:

  • 啊,好吧,这影响了我的记忆。我正在使用 webpack 代理 devServer,所以当我转到 8080 时,它不会点击应用程序。我必须在 8181 devServer: { historyApiFallback: true, proxy: { '/api*': 'http://localhost:8181' } }
猜你喜欢
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 2018-08-04
  • 2013-03-04
  • 2017-12-24
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多