node.js - متوجه شدم درخواست CRUD کار نمیکند: Nodejs
من برای یک API نودجیاس کار میکنم و این یک فایل هندلر است:
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;
فایل مدل مربوطه عبارت است از:
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}`);
}
}
}
وقتی سعی میکنم همه محصولات را فهرست کنم، این خوب کار میکند، اما نمیتوانم فقط یک محصول را برای نمایش بگیرم.
API اینجا است در صورتی که کسی بخواهد نگاهی بیندازد: https://github.com/Chaklader/StorefrontAPI
کوئری SQL در ترمینال Postgres کار میکند. مشکل اینجا چیست؟
پاسخ شماره ۱
رشته پرس و جوی دوم خود را با این جایگزین کنید:
const sql = 'SELECT * FROM products WHERE id=$1';
پاسخ شماره ۲
این مشکل به این دلیل بود که من پارامتر را با URL ارائه دادم، بنابراین باید آن را مطابقاً استخراج کنم و نه از بدنه. این کد است که کار میکند:
const show = async (_req: Request, res: Response) => {
const c = parseInt(_req.params.id);
const product = await store.show(c);
res.json(product);
};
علاوه بر این، پرسوجوی SQL ذکر شده در پاسخ بالا نادرست است و میتوان از آن همانطور که در سؤال ارائه شده استفاده کرد.
