【问题标题】:Getting an error when trying to display multiple html pages (express)尝试显示多个 html 页面时出错(快速)
【发布时间】:2020-08-24 07:48:17
【问题描述】:

我有一个带有名为“关于”的链接的 index.html。单击 About 时,我只收到错误 Cannot GET /about。这里有什么问题?

我的代码:

const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();

router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});

router.get('/about',function(req,res){
res.sendFile(path.join(__dirname+'/about.html'));
});

app.use('/', router);
app.listen(process.env.port || 3000);
console.log('Running at Port 3000');

在 index.html 中:

<a href="/about">About</a>

【问题讨论】:

  • 你能展示一下你用过的&lt;a&gt;吗?
  • @ChrisG 关于
  • 使用您的确切代码对我来说很好。地址栏是http://localhost:3000/about吗?
  • @ChrisG 现在似乎可以工作了..奇怪:D
  • 添加/about路由后是否重启了服务器?

标签: javascript express


【解决方案1】:

您可以创建静态文件夹名称 public。之后就可以使用这个中间件了。 app.use('/static', express.static(path.join(__dirname, 'public')))

现在您可以将 index.html 和 about.html 放入名为“public”的新文件夹中。 在此之后,我认为所有问题都会解决。

Static Files Examples

Routing Examples

【讨论】:

  • 虽然为静态文件设置文件夹确实更好(并且可以说使用视图更好),但这并不能真正解决 OP 的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多