Develop web service with NodeJS

npm init –yes
npm i express
npm i -g nodemon
npm install –save express@4.16.3 mysql@2.15.0 body-parser@1.18.2
you can get version info from https://www.npmjs.com/package/body-parser
https://www.npmjs.com/package/mysql

C:\Hans\first-app>nodemon index.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node index.js
Listening on port 3000
[nodemon] restarting due to changes…
[nodemon] starting node index.js
Listening on port 3000

C:\Hans\first-app>set PORT=5000 (on Linux use export PORT=5000)

check records on http://localhost:3000/api/courses
use postman to POST data

Here is the code:

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

app.use(express.json());

const courses = [
    { id: 1, name: 'course1' },
    { id: 2, name: 'course2' },
    { id: 3, name: 'course3' },
];

app.get('/', (req, res) => {
    res.send('Hello World!!!');
});

app.get('/api/courses', (req, res) => {
    res.send(courses);
});


app.post('/api/courses', (req, res) => {
    const course = {
        id: courses.length + 1,
        name: req.body.name
    };
    courses.push(course);
    res.send(course);
});


app.get('/api/courses/:id', (req, res) => {
   let course = courses.find(c => c.id === parseInt(req.params.id));
   if (!course) res.status(404).send('the id not found');
   res.send(course)
});

//port
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}....`))

Leave a Reply

Your email address will not be published. Required fields are marked *