H1: REST API Demo

  1. Looome projekt Node.js-iga

installime express

npm install express cors
// kasutame moduleid
const express = require('express');
const cors = require('cors');

// loome leht 
const app = express();

app.use(cors());
app.use(express.json());

const widgets = [
    { id: 1, name: "Kirill", age: "18"},
    { id: 2, name: "David", age: "18"},
    { id: 3, name: "Martin", age: "18"}

]

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 mot found"})
    }
    res.send(widgets[req.params.id - 1])
    
    
})

app.post('/widgets', (req, res) => {
    if (!req.body.name || !req.body.age) {
        return res.status(400).send({ error: 'One or all params are missing' })
    }
    let newWidget = {
        id: widgets.length + 1,
        age: req.body.age,
        name: req.body.name
    }
    widgets.push(newWidget)
    res.status(201).location('localhost:8080/widgets/' + (widgets.length - 1)).send(
        newWidget
    )
})
//kustutamine
app.delete('/widgets/:id', (req, res) => {
    if (typeof widgets[req.params.id -1] === 'undefined'){
        return res.status(404).send({ error: "Widget mot found"})
    }
    widgets.splice(req.params.is -1,1)
    res.status(204).send()
})
app.listen(8080, () => {
    console.log(`API up at: http://localhost:8080`)
})

Lisamine:

Andmete saatmine:

Delete: