Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
Encuentro que la solicitud CRUD no funciona: Nodejs

Trabajo para una API de Nodejs y este es un archivo de controlador:

 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;

El archivo del modelo respectivo es:

 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}`); } } }

Cuando trato de indexar todos los productos, esto funciona bien, pero no puedo buscar solo un producto para mostrar.

ingrese la descripción de la imagen aquí

La API está aquí en caso de que alguien quiera mirar: https://github.com/Chaklader/StorefrontAPI

La consulta SQL funciona en la terminal de Postgres. ¿Cuál es el problema aquí?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Reemplace su segunda cadena de consulta con esto:

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

0

Este problema fue que proporcioné el parámetro con la URL, tendré que extraerlo en consecuencia y no del cuerpo. Este es el código que funciona:

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

Además, la consulta SQL mencionada en la respuesta anterior es incorrecta y se puede usar tal como se proporciona en la pregunta.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!