繁体   English   中英

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

[英]Using relative Path in NodeJS and express

我目前正在尝试找出nodejs并表达。

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

访问 /login 时,我想重定向到 login.html 文件。

app.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, '/login/login.html'));
})

工作安静得很好。

我有 css 直接在 header 中,现在我想从 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

我如何实际使用提供的 static 文件? 我应该在 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>

您需要将 static 路径更改为并允许 express 提供 static 文件

//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'));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM