Cannot GET /api/products/1

Issue

I’m running a simple backend server to select a single product from my products.json database. However, it keeps sending me this message: Cannot GET /api/products/1

Here is my server.js code:

const express = require('express');
const products = require('./data/products')

const app = express();

app.get('/', (req, res) => {
    res.send('API is running...');
});
app.get('/api/products', (req, res) => {
    res.json(products);
});
app.get('/api/products:id', (req, res) => {
    const product = products.find((p) => p._id === req.params.id);
    res.json(product);
});

app.listen(5000, console.log('Server running on port 5000'));

Solution

Try

app.get('/api/products/:id', (req, res) => {
    const product = products.find((p) => p._id === req.params.id);
    res.json(product);
});

You were missing a "/" between products and :id

Answered By – Jeffrey Ram

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published