简体   繁体   English

Node.js Restful API:如何通过ID获取数据

[英]Nodejs restful API: how to get data by id

I am building a node/express app and I want to return a specific data by handling id params. 我正在构建一个节点/表达应用程序,我想通过处理id参数来返回特定的数据。

Here is the structure of my files: 这是我文件的结构:

    app.js
    ./src
      /db/users.js
      controllers
      models
    ./tests

users.js users.js

const users = [
  {
    id: 1,
    email: 'sarah@gmail.com',
    name: 'Sarah',
    phone: 09000082

  },
  {
    id: 2,
    email: 'dklf@gmail.com',
    name: 'Kelavos',
    phone: 08522222

  },
];

export default users;

My model 我的模特

import users from '../db/users';

const findUser = id => users.find(x => x.id === id);

export default { findUser };

My controller 我的控制器

import userModel from '../models/user.model';

class UserController {

  /**
 * Get one user
 * @param {object} req
 * @param {object} res
 */

  getUser(req, res) {
    const id = parseInt(req.params.id);
    console.log(`Test: ${  userModel.findUser(req.params.id)  } and ${  req.params.id}`);
    return res.status(201).send({
      status: 'success',
      data: userModel.findUser(id),
    });
// return Not found and 404 for an non existing id or if id !== int
    if (isNaN(id) || !id) {
      return res.status(404).send({
        status: 'error',
        error: 'Not found',
      });
    }
  }
}

const userController = new UserController();
export default userController;

This is my app.js 这是我的app.js

import express from 'express';
import bodyParser from 'body-parser';
import UserController from './src/controllers/user.controller';

// set up the express app
const app = express();

// Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const baseUrl = '/api/v1/';

app.get(`${baseUrl}users/:id`, UserController.getUser);

export default app;

I've set the port and other config in a server.js file 我已经在server.js文件中设置了端口和其他配置

If I run the app and test the endpoint with Postman I only get status: "success" Not that I comment the second bloc of UserController class if (isNaN(id) || !id) because with it ESLint warn me of Unreachable code detected 如果我运行该应用程序并使用Postman测试端点,那么我只会得到status: "success"不是说if (isNaN(id) || !id) ,则注释UserController类的第二个块,因为ESLint会警告我Unreachable code detected

What is wrong with my code that is preventing me to return the result for a given user? 我的代码有什么问题,导致我无法为给定用户返回结果?

You are using object destructuring wrong. 您使用的对象解构错误。 In your controller, make this change: 在您的控制器中,进行以下更改:

const id = req.params.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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