node.js - 在 NodeJS 中使用相对路径并表达
问题描述
我目前正在尝试找出nodejs并表达。
目前,我在本地机器上运行了一个小型示例项目。
访问 /login 时,我想重定向到 login.html 文件。
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, '/login/login.html'));
})
工作安静得很好。
我将 css 直接放在标题中,现在我想从 html 站点本身访问一个共享文件夹。
文件结构:
- project
+--- node_modules
+--- package.json
+--- index.js
+--- shared/
+--- css/
+--- style.css
+--- images/
+--- login/
+--- login.js
+--- login.html
我在 express 文档中找到了以下解决方案:https ://expressjs.com/en/starter/static-files.html它是 - 至少我认为 - 我需要的。
目前我只使用 index.js 和 login.js
我如何实际使用提供的静态文件?我应该在 index.js 中提供它们吗?
index.js:
const express = require('express');
var path = require('path');
const cors = require('cors');
const port = process.env.PORT || 3000;
const app = express();
app.use(cors());
app.use('/static', express.static(path.join(__dirname + './static')));
app.get('/', async (req, res) => {
res.send('hello world!');
})
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, '/login/login.html'));
})
app.listen(port, () => {
console.log('listening on http://localhost:' + port);
})
登录.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="shared/css/style.css">
</head>
<body>
<div class="login-form">
<h1>Login Form</h1>
<form action="auth" method="POST">
<input autocomplete="off" type="text" name="username" placeholder="Username" required>
<input autocomplete="off" type="password" name="password" placeholder="Password" required>
<input type="submit">
</form>
</div>
</body>
</html>
解决方案
您需要将静态路径更改为并允许 express 提供静态文件
//here login is the folder name which contain index.html file so you need to define that path
var public = path.join(__dirname, 'login');
app.use(express.static(public));
app.get('/login', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
推荐阅读
- python - Pycharm 无法自动完成某些模块
- python-3.x - 下载链接中的空格 python beautifulsoup
- python - 如何从给定的输入中检索日期
- c# - C# MongoDb 驱动程序包含子对象
- django - 如何过滤/获取 2 个单词 __str__
- r - 需要 TRUE/FALSE 的 if() 缺失值出错,但内部实际上有一个布尔参数
- html - 将 HTML 放在 Rails 助手中
- sql-server - 从数据库项目文件中插入二进制种子数据
- android - 如何以表格形式显示excel数据?
- c# - AdomdConnection 可以接受令牌吗