[英]Error: Cannot get orders: TypeError: Cannot read properties of undefined (reading 'connect')
I'm trying to build an API with express and pg.我正在尝试使用 express 和 pg 构建 API。 Whenever I try to access an endpoint that is related to a query to the database I get the error above.
每当我尝试访问与数据库查询相关的端点时,都会出现上述错误。
My handler function is as follows:我的处理函数如下:
import { Request, Response, Router, NextFunction } from 'express';
import { Orders } from '../models/order';
const orders = new Orders;
const index = async (_req: Request, res: Response, next: NextFunction) => {
try {
const ordersList = await orders.index();
res.json(ordersList);
} catch (err) {
next(err)
}
}
const ordersRoute = Router();
ordersRoute.get('/', index);
This handler refers to the following model:此处理程序引用以下模型:
import { Pool } from 'pg';
client = new Pool({
host: POSTGRES_HOST,
database: POSTGRES_DB,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
port: parseInt(POSTGRES_PORT as string, 10)
export class Orders {
async index(): Promise<Order[]> {
try {
const conn = await client.connect();
const sql = 'SELECT * FROM orders';
const result = await conn.query(sql);
conn.release();
return result.rows;
} catch (err) {
throw new Error(`Cannot get orders: ${err}`);
}
}
}
anytime I try to access the endpoint I get任何时候我尝试访问我得到的端点
Error: Cannot get orders: TypeError: Cannot read properties of undefined (reading 'connect')
错误:无法获取订单:TypeError:无法读取未定义的属性(读取“连接”)
in the console.在控制台中。 any idea how to fix ?
知道如何解决吗?
So how things work in your case.那么在你的情况下事情是如何运作的。
All modules are read by nodejs starting from your index one by one from top to bottom. nodejs从你的索引开始,从上到下一一读取所有模块。
In your script, you declare client
and then export a class
.在您的脚本中,您声明
client
,然后导出一个class
。 In that case, your client
is setup, then you export a class, and that file is completed, meaning that the only thing that remains is the exported
thing.在这种情况下,您的
client
已设置,然后您导出一个类,该文件已完成,这意味着唯一剩下的就是exported
的东西。 So when you try to use the exported
class, you'll not have the same context as in your module.因此,当您尝试使用
exported
的类时,您将不会拥有与模块中相同的上下文。
You need to export the client
too and import it where you need that class or to include client
definition inside the class您还需要导出
client
并将其导入您需要该类的位置或在类中包含client
定义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.