因此,我只是第一次尝试es6并希望使用新的类,但我遇到了一个奇怪的问题。所有类都可以正常工作,并且可以很好地写入/读取它们的类变量但是一个班级的表现并不好。es6类变量无法读取(无法读取属性'...'的未定义)
我目前收到此错误:
TypeError: Cannot read property 'product' of undefined at getProducts (***/controllers/ProductController.js:41:13)
我正在写使用的平均堆栈学校分配的REST API。
总之什么目前发生
index.js
// dependencies
const Api = require('./routes/api')
class Rest
{
constructor()
{
this.api = new Api()
this.init()
}
init()
{
... // express server configuration
// routes
this.routes()
}
// set routes
routes()
{
app.use('/api', this.api.getRouter())
}
}
new Rest()
/routes/api.js
// dependencies
const express = require('express')
const Products = require('./api/products')
class Api
{
constructor()
{
this.router = express.Router()
this.products = new Products()
this.routes()
}
getRouter() { return this.router }
routes()
{
// product routes
this.router.use('/products', this.products.getRouter())
}
}
// return routes
module.exports = Api
路线/ API/products.js
// dependencies
const express = require('express')
const productController = require('../../controllers/ProductController')
class Product
{
constructor()
{
this.router = express.Router()
this.controller = new productController()
this.routes()
}
getRouter() { return this.router }
// set header options
setCollectionOptions(req, res, next)
{
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
next()
}
// set routes
routes()
{
this.router.route('/')
.options([this.setCollectionOptions, this.controller.getOptions])
.get([this.setCollectionOptions, this.controller.getProducts])
}
}
// return routes
module.exports = Product
模型/ Product.js
// dependencies
const mongoose = require('mongoose')
const mongoosePaginate = require('mongoose-paginate')
// create schema for model
const productSchema = new mongoose.Schema({
name: String,
sku: String,
price: String,
created_at: { type: String, default: Date.now },
updated_at: { type: String, default: Date.now }
})
productSchema.plugin(mongoosePaginate)
// export model
module.exports = mongoose.model('Products', productSchema)
控制器/ ProductController.js
// dependencies
const express = require('express')
class ProductController
{
constructor()
{
this.product = require('../models/product')
}
getProducts(req, res, next)
{
this.product.find() // error occurs here!
... // rest of the code
}
}
在this.product.find()
当我console.log(this.product)
将出现错误,之后立即我设置它,它只是返回罚款。但是,当我通过GET请求页面http://localhost:port/api/products
时,我收到此错误。
另外,当我尝试使用ProductController中的方法时,它会导致相同的错误。例如:
class ProductController
{
constructor()
{
this.product = require('../models/product')
}
init()
{
console.log('hi!')
}
getProducts(req, res, next)
{
this.init()
... // rest of code
}
}
在此先感谢。
虽然你需要将它绑定到'this.controller'。也许箭头功能是一个更简单的解决方案。 – Bergi
@Bergi,谢谢,关于接收器的好消息。也添加了箭头示例。 – Bakkot
如果你不知道参数的数量或者有太多拼写出来,你也可以使用rest/spread语法:'(... args)=> this.controller.getProducts(... args) ' – Bergi