在 NodeJS 中使用相对路径并表达

莱希内里奥

我目前正在尝试找出 nodejs 和 express。

目前,我在本地机器上运行了一个小型示例项目。

当访问 /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 中提供它们吗?

索引.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'));
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章