Harjutus 1: REST API demo

1. Paigalda Node.js
2. Loo töölauale kaust restapi 
3. Käivita koodiredaktor (nt VS Code, WebStorm vms) ja ava see kaust projektina
4. Loo kausta fail index.js järgneva sisuga:

const express = require('express');
const cors = require('cors');
const app = express();
 
app.use(cors());        
app.use(express.json()) 
 
const widgets = [
    { id: 1, name: "Cizzbor", price: 29.99 },
    { id: 2, name: "Woowo", price: 26.99 },
    { id: 3, name: "Crazlinger", price: 59.99 },
]
 
app.get('/widgets', (req, res) => {
    res.send(widgets)
})
 
app.get('/widgets/:id', (req, res) => {
    if (typeof widgets[req.params.id - 1] === 'undefined') {
        return res.status(404).send({ error: "Widget not found" })
    }
    res.send(widgets[req.params.id - 1])
})
 
app.post('/widgets', (req, res) => {
    if (!req.body.name || !req.body.price) {
        return res.status(400).send({ error: 'One or all params are missing' })
    }
    let newWidget = {
        id: widgets.length + 1,
        price: req.body.price,
        name: req.body.name
    }
    widgets.push(newWidget)
    res.status(201).location('localhost:8080/widgets/' + (widgets.length - 1)).send(
        newWidget
    )
})
 
app.listen(8080, () => {
    console.log(`API up at: http://localhost:8080`)
})

5. Käivita koodiredaktoris terminal ja seal järgnevad käsud:

1. npm init -y
2. npm i express cors
3. node . 

6. Tee terminalis xh’ga GET päring vastu API-t:

7.  Tee terminalis xh’ga GET päring vastu API-t, mis tagastab kõik vidinad:

8. Tee terminalis xh’ga POST päring vastu API-t, mis lisab uue vidina:

9. Tee terminalis xh’ga POST päring vastu API-t, mis kustutab ühe vidina:

et