【问题标题】:I find the CRUD request doesn't work: Nodejs我发现 CRUD 请求不起作用:Nodejs
【发布时间】:2021-10-11 19:43:03
【问题描述】:

我为 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 终端中运行。这里有什么问题?

【问题讨论】:

    标签: node.js typescript visual-studio-code


    【解决方案1】:

    将您的第二个查询字符串替换为:

    const sql = 'SELECT * FROM products WHERE id=$1';
    

    【讨论】:

    • 我希望这可以工作,但是,它仍然没有按预期提供结果。我提供了 repo,所以如果你想看看,这会很有帮助。
    【解决方案2】:

    这个问题是因为我提供了带有 URL 的参数,我需要相应地提取它,而不是从正文中提取。这是有效的代码:

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

    另外,上面答案中提到的SQL查询不正确,可以按照问题中提供的方式使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 2017-02-23
      • 2022-10-09
      • 2022-08-03
      • 2019-12-23
      相关资源
      最近更新 更多