const express = require('express');
const app = express();
app.get('/',(req,res) =>{ // result shows on localhost:3000
res.send('hello world');
});
app.get('/api/courses',(req,res) =>{ // result shows on localhost:3000/api/courses
res.send(\[1,2,3\]);
});
app.get('/api/courses/:id',(req,res) =>{ // result does not show on localhost:3000/api/courses/1
res.send(req.param.id);
});
//PORT
const port= process.env.PORT||3000;
app.listen(port,()=\>console.log(\``Listening to port ${port}...`\`));
I seem to be getting result for the first 2 get functions but not the ID, i get the following error Cannot GET /api/courses/1 how do i fix it ?
was expecting output of id as '1' to display
You did have a syntax error in your console.log() line when starting the server: console.log(``Listening to port ${port}...\) is not valid JavaScript (this might have been just an editing error when you pasted your code here).
But most important, you are missing an s in param. It should be req.params.id.
Below code does work for me. I've tested it using Postman.
import express from "express";
const app = express();
app.get("/", (req, res) => {
// result shows on localhost:3000
res.send("hello world");
});
app.get("/api/courses", (req, res) => {
// result shows on localhost:3000/api/courses
res.send([1, 2, 3]);
});
app.get("/api/courses/:id", (req, res) => {
// // result does not show on localhost:3000/api/courses/1 res.send(req.param.id);
res.send(`This handler has received the value ${req.params.id} for ID`);
});
//PORT
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening to port ${port}...`));