Search code examples
node.jssqliteexpressexpress-handlebars

Web page renders, but crashes the server the first time, then renders without crashing the server subsequent times


I am using NodeJS, Express, and Express-handlebars to render a webpage using data pulled from an SQLITE3 database.

The code works, and the page renders properly, but the first time it loads, it crashes my server with this error: TypeError: Cannot read property 'user_name_tag' of undefined

The error says it cannot read this property, but displays the information from it correctly before the server crashes. However, if restart the server and reload the page, it doesn't crash, it also doesn't crash if I open a new instance with a different user and different data set after the initial load.

Here's the index.js code:

const express = require('express');
const app = express();
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('../database.sqlite');
const exphbs = require('express-handlebars');
const hbs = exphbs.create({
    defaultLayout: 'main',
//custom helpers
    helpers: {
        iff: function(a, b, opts) {
            if (a == b) {
                return opts.fn(this);
            } else {
                return opts.inverse(this);
            }
        }
    }
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

app.get('/:userid', async (reg, res) => {
    const findUser = reg.params.userid;
    console.log('I am findUser ',findUser);
      let query = "SELECT users.user_id, users.balance, users.user_avatar, users.user_name_tag, user_collections.user_stamina, user_collections.collection_switch,";
      query += "COALESCE((SELECT SUM((SELECT (currency_shops.cost * user_items.amount) FROM currency_shops WHERE currency_shops.id = user_items.item_id)) FROM user_items WHERE user_items.user_id = users.user_id GROUP BY user_items.user_id), 0) as totalItems, ";
      query += "COALESCE((SELECT SUM((SELECT (craft_shops.cost * user_craft_items.amount) FROM craft_shops WHERE craft_shops.id = user_craft_items.item_id)) FROM user_craft_items WHERE user_craft_items.user_id = users.user_id GROUP BY user_craft_items.user_id), 0) as totalCraftItems, ";
      query += "COALESCE((SELECT SUM((SELECT (stonk_shops.cost * user_stonks.amount) FROM stonk_shops WHERE stonk_shops.id = user_stonks.item_id)) FROM user_stonks WHERE user_stonks.user_id = users.user_id GROUP BY user_stonks.user_id), 0) as totalStonks ";
      query += "FROM users, user_collections WHERE users.user_id = ? AND users.user_id = user_collections.user_id";
    await db.get(query, [findUser], (err, row ) => {
            (err, rows) => {       
        };
                res.render('profile', {
                title: 'User Profile',
                user_name: ([row.user_name_tag]),
                user_id:([row.user_id]),
                user_balance:([row.balance]),
                user_avatar:('src','https://cdn.discordapp.com/avatars/' + [row.user_id] + '/' + [row.user_avatar] + '.png'),
                user_stamina:([row.user_stamina]),
                user_networth:([row.balance + row.totalItems + row.totalCraftItems + row.totalStonks]),
                collection_switch:([row.collection_switch]),    
                isCollectionOn:([row.collection_switch]),
            }) 

   });

});
const PORT = process.env.PORT || 6999; 
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Here is the HTML:

<h1>Welcome to your profile page {{user_name}} !</h1>
<h1>This is your ID number {{user_id}} .</h1>
<h1>This is your current credits balance {{user_balance}} .</h1>
<h1><img src='{{user_avatar}}'>This is your face!</img></h1>
<h1>This is your current stamina {{user_stamina}} .</h1>
<h1>This is your networth {{user_networth}}</h1>
{{#iff isCollectionOn 0}}
<h1>Your collection switch is set to {{collection_switch}}, you are free to collect!</h1>
{{else}}
<h1>This worked, congrats!</h1>
{{/iff}}

I hope this enough information, feel free to ask me to provide more if needed.


Solution

  • So I was using sublime and decided to switch to visual studio code. Visual studio codes linter answered my question. It told me my await was doing nothing and suggested deleting a redundant function I had in there for some unknown reason(probably leftovers of my trying different things). It was solved by changing this:

    await db.get(query, [findUser], (err, row ) => {
                (err, rows) => {       
            };
                    res.render('profile', {
    

    To this

        db.get(query, [findUser], (err, row ) => {
                res.render('profile', {
    

    Also, I should note, it appears my favicon had something to do with some of the crashes I was getting. I found out that with Express, favicons are handled with middleware inside the index.js file rather than the html file.