首页 > 解决方案 > 为什么它将与数据库的连接检测为未定义?

问题描述

我正在制作一个基本的 API,但不明白为什么它会给我一个错误。

TypeError: Cannot read property 'conneDB' of undefined

import { json, Request, Response } from "express";


import { ConnectionDB } from "../ConnectionDB";
import  Post  from "../interfaces/Ipost.interface";


export class PostsController {
    private conneDB = new ConnectionDB()


async getAllPosts(req: Request, res: Response) {
    const posts = await this.conneDB.connection.query('SELECT * FROM posts')
    return res.json(posts[0])
}

async getPost(req: Request, res: Response){
    const idPost = req.params.postId;
    const post = await this.conneDB.connection.query('SELECT * FROM posts WHERE id = ?', [idPost])
    return res.json(post[0])
}

async createPost(req: Request, res: Response) : Promise<Response>{
    const newPost: Post = req.body;
    await this.conneDB.connection.query('INSERT INTO posts SET ?', [newPost])
    return res.json({
        message: 'Post created'
    });
}
}

标签: mysqlnode.jstypescriptexpress

解决方案


推荐阅读