Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
I find the CRUD request doesn't work: Nodejs

I work for an Nodejs API and this is an handler file:

import express, { Request, Response } from 'express';
import { ProductStore, Product } from '../models/products';

const store = new ProductStore();

/* 
export type Product = {
    id?: number;
    name: string;
    price: number;
    category?: string;
};
*/

const index = async (_req: Request, res: Response) => {
    const products = await store.index();
    res.json(products);
};

const show = async (_req: Request, res: Response) => {
    const product = await store.show(_req.body.id);
    res.json(product);
};

const productRoutes = (app: express.Application) => {
    app.get('/products', index);
    app.get('/products/:id', show);
    app.post('/products', create);
    app.delete('/products', destroy);
};

export default productRoutes;

The respective model file is:

import client from '../database';

export type Product = {
    id?: number;
    name: string;
    price: number;
    category?: string;
};

export class ProductStore {
    async index(): Promise<Product[]> {
        try {
            // @ts-ignore
            const conn = await client.connect();
            const sql = 'SELECT * FROM products';

            const result = await conn.query(sql);

            conn.release();

            return result.rows;
        } catch (err) {
            throw new Error(`Could not GET products with error: ${err}`);
        }
    }

    async show(id: number): Promise<Product> {
        try {
            const sql = 'SELECT * FROM products WHERE id=($1)';
            // @ts-ignore
            const conn = await client.connect();

            const result = await conn.query(sql, [id]);

            conn.release();

            return result.rows[0];
        } catch (err) {
            throw new Error(`Could not find product ${id} with error: ${err}`);
        }
    }
}

When I try to index all the products, this works well, but, I can't fetch only one product for show.

enter image description here

The API is here in case someone want to look: https://github.com/Chaklader/StorefrontAPI

The SQL query works in the Postgres terminal. What's the issue here?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Replace your second query string with this:

const sql = 'SELECT * FROM products WHERE id=$1';
over 4 years ago · Santiago Trujillo Denunciar

0

This issue was as I provided the parameter with the URL, I will need to extract it accordingly and not from the body. This is the code that works:

const show = async (_req: Request, res: Response) => {

    const c = parseInt(_req.params.id);
    const product = await store.show(c);
    res.json(product);
};

Besides, the SQL query mentioned in the answer above is incorrect and can be used as it is provided in the question.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda