javascript - 在 Express 中提供静态 HTML 文件的不同路径

标签 javascript node.js express

只是一个简短的问题。假设我有 2 个不同的静态 HTML 文件要在 Express 中提供,index.htmlcontact.html。我一直在摆弄,我目前使用这个准系统 Express 代码来为他们服务:

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

const app = express();

app.use(express.static('public'))

app.get('/', function (req, res) {
  res.sendFile('/index.html');
});

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/public/contact.html');
});

app.listen(3000, function () {
  console.log('runnning on port 3000')
});

问题是,我尝试使用

服务contact.html
app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/contact.html');
});

但它总是求助于根目录而不是公共(public)目录。 OTOH,我可以服务器 index.html 就好了,而不必在响应中显式添加 /public

有人能告诉我这是什么原因吗?

谢谢。

最佳答案

对于给定的文件结构:

yourapp
 |-- contact.html
 |-- index.html
 `-- server.js

下面的代码可以正常工作:

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

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/contact.html');
});

假设 index.htmlcontact.html 都具有读取权限。

请记住,sendFile 需要一个绝对路径 并且__dirname 是指您的应用程序目录。确保根据文件位置提供引用。

关于javascript - 在 Express 中提供静态 HTML 文件的不同路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535496/

相关文章:

javascript - 使用 Node js 在 Redis 中存储以 id 作为键的对象

javascript - 使用角色和特定用户ID来限制在react/node/express/mysql中可以查看哪些部分?

node.js - 自动化测试的 NodeJS 代码覆盖率

javascript - Node.js Object 对象没有方法 'hasOwnProperty'

javascript - React/webpack 有条件返回 require.ensure 组件(代码分割)

node.js - 使用 fetch API 时如何记录实际的请求 header

node.js - index.jade 没有出现在本地主机上

javascript - 打破nodejs中的循环

javascript - 在 FullCalendar dayClick 上触发 jQuery Qtip

javascript - 为什么我不能将 for 循环分配给变量?