简体   繁体   中英

Error: Cannot get orders: TypeError: Cannot read properties of undefined (reading 'connect')

I'm trying to build an API with express and pg. 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')

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.
In your script, you declare client and then export a 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. So when you try to use the exported class, you'll not have the same context as in your module.

You need to export the client too and import it where you need that class or to include client definition inside the class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM