nodejs 与 Express 和 ejs 在 ubuntu 和 rasbian 上有所不同

问题描述 投票:0回答:1

我想在 Node.js 上使用 Express 和 EJS 构建一个小日历。我在我的笔记本电脑(Ubuntu)上启动,一切运行良好。
之后,我将项目克隆到我的 Raspberry 上,它将为我的家庭网络中的这个小型 Web 服务器提供服务。但即使它抱怨的对象内的“数据”存在,它也会抛出错误。

index.ejs:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Little Advent Calendar</title>
        <link rel="stylesheet" type="text/css" href="/main.css"  />
    </head>
    <body class="background">
        <div class="center">
            <section >
                <h2 class="title" align="center"> <%= day %>. Dezember</h2>
                <p class="btn-style" align="center">
                    <a href="/<%= day %>" type="button" class="a-btn">Öffnen</a>
                </p>
                
            </section>
        </div>
    </body>
</html>

server.js(运行网络服务器):

...
app.use(express.static(path.join(__dirname, '/public/')));
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));

app.get('/', async(req, res) => {
    let date_ob = new Date();
    let day = date_ob.getDate();
    res.render('main/index', {"day": day});
    
})

app.listen(port);

在两台机器上,网页看起来是一样的。通过从 server.js 传递的 JSON 对象可以正确显示日期(日)。
但在我的 Raspberry 上,它抛出以下错误,它没有完全崩溃,但似乎出现了问题:

ReferenceError: /home/pi/Desktop/advent-calendar/views/main/index.ejs:10
    8|      <div class="center">
    9|          <section >
 >> 10|                 <h2 class="title" align="center"> <%= day %>. Dezember</h2>
    11|                 <p class="btn-style" align="center">
    12|                     <a href="/<%= day %>" type="button" class="a-btn">Öffnen</a>
    13|                 </p>

day is not defined
    at eval ("/home/pi/Desktop/advent-calendar/views/main/index.ejs":12:26)
    at index (/home/pi/Desktop/advent-calendar/node_modules/ejs/lib/ejs.js:703:17)

为 Raspberry 和 e.g. 提供的 JSON 有什么区别吗? Node.js 中的 Ubuntu?

这就是网页的样子。它明确地打印来自 server.js 的 day 变量中的日期

html node.js express raspberry-pi ejs
1个回答
0
投票

我在这里找到了问题。主要原因是浏览器额外爬行网络服务器以获得

favicon.ico

当这对我来说并不总是一个问题时,因为我还通过添加以下内容实现了获取当天当前数据的路线:

app.get('/:day', async(req, res) => {
        var dayNum = req.params.day
        var day = today();

        // decide the type and render the specific page
        if (day.type == "number" || day.type == "Number") {
            res.render('main/number', { "day": day });
        } else {
            // default page if nothing matches (fallback)
            res.render('main/index');
        }
})

插入检查 url 中提供的参数是否不是 favicon.ico 为我解决了这个问题。因此,即使我仍在索引页面上,浏览器也会调用此路由。

引发

day is not defined
的错误是因为我错过了在上面的路由中插入索引页的
{ day: day }
。因此从技术上讲,由于 favicon.ico 调用,我的索引页被渲染了两次。第一次有正确的值,第二次没有该值。

© www.soinside.com 2019 - 2024. All rights reserved.