K
K
kirillmoroz2021-04-18 18:56:50
Node.js
kirillmoroz, 2021-04-18 18:56:50

Node js, Handlebars, why Cannot read property 'title' of undefined?

Hello! I am writing a site on a node at the rate. I use express and handlebars. It seems that I did everything the same, but the page does not load. It hangs when loading, and when I stop loading, the data is displayed, but the styles are not loaded, and an error occurs in the console ( node:7412 ) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'title' of undefined at C:\Users\kill0\Desktop \psyholog\routes\blog. js:19:31 (Use node --trace-warnings ... to show where the warning was created) ( node:7412) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_reje... ). (rejection id: 1) ( node:7412 ) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.`index.js

index.js

const path = require('path')
const express = require('express')
const exphbs = require('express-handlebars')
const mainRoutes = require('./routes/main')
const blogRoutes = require('./routes/blog')
const feedbackRoutes = require('./routes/feedback')
const messageRoutes = require('./routes/message')

const app = express()

const hbs = exphbs.create({
    defaultLayout: 'main',
    extname: 'hbs'
})

app.engine('hbs', hbs.engine)
app.set('view engine', 'hbs')
app.set('views', 'pages')

app.use(express.static(path.join(__dirname, 'public')))
app.use(express.urlencoded({extended: true}))
app.use('/', mainRoutes)
app.use('/blog', blogRoutes)
app.use('/feedback', feedbackRoutes)
app.use('/message', messageRoutes)

const PORT = process.env.PORT || 3000

app.listen(3000, () => {
    console.log(`Server is running on port ${PORT}`)
})

blog.js

const {Router} = require('express')
const Publication = require('../models/publication')
const router = Router()

router.get('/', async (req, res) => {
    const publications = await Publication.getAll()
    res.render('blog', {
        title: 'Блог',
        isBlog: true,
        publications
    })

    // const np = new Publication(
    //     'Глубинные убеждения, или как я попрощалась с страхом высоты. Часть 2.', 
    //     './img/post_2.jpg',
    //     'Привет! С радостью поделюсь с вами секретом, как я поняла и устранила причину своего страха высоты. Кстати, это может помочь вам, если вы захотите узнать себя чуточку лучше.'
    // ).save()
})

router.get('/:id', async (req, res) => {
    const publication = await Publication.getById(req.params.id)
    res.render('publication', {
        title: `Пост ${publication.title}`,
        publication
    })
}) 


module.exports = router

blog.hbs

{{#if publications.length}}
{{#each publications}}
<div class="blog">
    <div class="blog__item">
        <p class="blog__item__title">{{title}}</p>
        <div class="blog__content">
            <img class="blog__content__img" src="{{img}}" alt="{{title}}">
            <p class="blog__content__text">{{text}}</p>
        </div>
        <a href="/blog/{{id}}" target="_blank">Открыть пост</a>
    </div>
</div>
{{/each}}
{{else}}
<p class="blog__title">Постов нет</p>
{{/if}}


publication.hbs

<div class="post">
    <h1>{{publication.title}}</h1>

    <img src="{{publication.img}}" alt="{{publication.title}}">

    <p>{{publication.text}}</p>
</div>

publication.js

const path = require('path')
const fs = require('fs')
const uuid = require('uuid')
const { runInThisContext } = require('vm')

class Publication {
    constructor(title, img, text) {
        this.title = title
        this.img = img
        this.text = text
        this.id = uuid.v4()
    }

    toJSON() {
        return {
            title: this.title,
            img: this.img,
            text: this.text,
            id: this.id
        }
    }

    async save() {
        const publications = await Publication.getAll()
        publications.push(this.toJSON())

        return new Promise((resolve, reject) => {
            fs.writeFile(
                path.join(__dirname, '../data', 'publications.json'),
                JSON.stringify(publications),
                (err) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve()
                    }
                }
            )
        })
    }

    static getAll() {
        return new Promise((resolve, reject) => {
            fs.readFile(
                path.join(__dirname, '../data', 'publications.json'),
                'utf-8',
                (err, content) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(JSON.parse(content))
                    }
                }
            )
        })
    }

    static async getById(id) {
        const publications = await Publication.getAll()
        return publications.find(p => p.id === id)
    }
}

module.exports = Publication

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question