Search code examples
javascriptnode.jsjsonexpressmockserver

Req Params Coming Back as Undefined


So I have a JSON file with mock data. I am trying to create a mock API server. I have one route that works fine:

const express = require("express");
const router = express.Router();
const data = require('../data/customers.json')

router.get("/",  (req, res) => {
    try {
        res.json({
            customers: data
        }).status(200);
    } catch(error) {
        console.error("ERROR: ",error);
        return error;
    }
})

I want the next route to be localhost/customers/:id, but for some reason the following route cannot read the req params when I test it out as localhost/customers/2 for example. But if I assign a test variable for 2 and use that in the find function instead, it works. So I've narrowed it down to an issue with the req.params. Here is the route (this is in the same file of course):

router.get("/:id", async (req, res) => {
    const { customer_id } = req.params;
    console.log('ID NUMBER', customer_id);
    try {
        const response = await data.find( customer => customer.id === customer_id);
        console.log(response)
        res.json(response).status(200);

    } catch(error) {
        console.error("ERROR: ",error);
        return error;
    }

})

If it helps at all here is a copy of my app.js:

'use strict';

const http = require('http');

const host = "127.0.0.1";
const port = 3000;

const cors = require('cors');
const morgan = require('morgan');

const express = require('express');
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(morgan('dev'));
app.use(cors());
app.use(express.static('public'));

const server = http.createServer(app);

server.listen(port, host, () => {
    console.log('Server has started.')
});

const rootController = require('./routes/index');
const customersController = require('./routes/customers');

app.use('/', rootController);
app.use('/customers', customersController);


Solution

  • The issue is in your router.get. You are referring to the param as customer_id. You need to refer to it in the same name of the param in the url router.get("/:id", async (req, res)... therefore your req.param is { id: '' }.

    Replace const { customer_id } = req.params; with const { id } = req.params;