简体   繁体   中英

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.

Here is the structure of my files:

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

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

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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