在页面呈现后,我收到错误消息:“TypeError:无法读取未定义的属性‘title’”。我在这里应用了我在 stackoverflow 上找到的一些解决方案,但我仍然遇到相同的错误。我已经包含了控制器文件、产品模型和路由器。 product-detail.ejs 确实呈现,但程序因错误而崩溃:“无法读取未定义的属性‘title’”。
//router:
router.get('/products/:productId', shopController.getProduct)
// end router
//Product model:
const fs = require('fs')
const path = require('path')
const p = path.join(__dirname, '../data', 'products.json')
const getProductsFromFile = (cb) => {
fs.readFile(p, (err, fileContent) => {
if (err) {
return cb([]);
}
cb (JSON.parse(fileContent))
})
}
module.exports = class Product {
constructor(title, imageUrl, description, price) {
this.title = title
this.imageUrl = imageUrl
this.description = description
this.price = price
}
save() {
this.id = Math.random().toString()
getProductsFromFile( products => {
products.push(this)
fs.writeFile(p, JSON.stringify(products), (err) => {
console.log(err)
})
})
}
static fetchAll(cb) {
getProductsFromFile(cb)
}
static findById(id, cb) {
getProductsFromFile(products => {
const product = products.find(p => p.id === id)
cb(product)
})
}
}
//end Product Model
// index.js
const path = require('path')
const http = require('http')
const express = require('express')
const socketio = require('socket.io')
const bodyParser = require('body-parser')
const errorController = require('./controllers/error')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
const port = process.env.PORT || 3000
const adminRoutes = require('./routes/admin')
const shopRoutes = require('./routes/shop')
const aboutRoutes = require('./routes/about')
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs')
app.set('views', 'views')
app.use(express.json())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false}))
app.use(express.urlencoded({ extended: false }))
app.use('/admin', adminRoutes)
app.use(shopRoutes)
app.use(aboutRoutes)
app.use(errorController.get404)
server.listen(port, () => {
console.log(`server is up on port ${port}!`)
})
// end index.js
<!-- product-detail.ejs -->
<%- include('../includes/head.ejs') %>
</head>
<body>
<%- include('../includes/nav.ejs') %>
<main class ="centered">
<h1><%= product.title %> </h1>
<hr>
<div>
<img src="<%= product.imageUrl%>" alt="<%= product.title %>">
</div>
<h2><%= product.price%></h2>
<p><%= product.description%></p>
<%- include('../includes/add-to-cart.ejs') %>
</main>
<%- include('../includes/end.ejs') %>
<!-- end -->
`
//function
static findById(id, cb) {
getProductsFromFile(products => {
const product = products.find(p => p.id === id)
cb(product)
})
}
// end function
//controller:
exports.getProduct = (req, res, next) => {
const prodId = req.params.productId
Product.findById(prodId, product => {
console.log(product)
res.render('shop/product-detail', {
product: product,
pageTitle: product.title, // <- throws error
path: '/products'
})
})
}
// end controller
`
答案 0 :(得分:0)
这个错误很标准,它只是意味着您的产品对象未定义。使用检查来确保它不会通过使用这样的可选链接而引发错误
product?.title