0

This topic is not a duplicate. Ignore the link, it won't guide you to solution.

First, the code. It's a list and CRUD to add, and delete items:

var express = require('express');
var app = express();
var path = require('path');

var cars = [];
var car = function (id, brand, model, year) {
    return { id: id, brand: brand, model: model, year: year };
}

app.use(express.urlencoded({
    extended: true
}));


app.get('/car', function (req, res) {
    res.sendFile(path.join(__dirname, 'CRUD/index.html'));
});

app.post('/car', function (req, res, next) {
    var id = req.body.id;
    var brand = req.body.brand;
    var model = req.body.model;
    var year = req.body.year;
    cars.push(car(id, brand, model, year));
    console.log("Added: id: " + cars.slice(-1)[0].id + " | brand: " + cars.slice(-1)[0].brand + " | model: " + cars.slice(-1)[0].model + " | year: " + cars.slice(-1)[0].year);

});

app.post('/car/:id', function (req, res, next) {
    var id = req.body.id;
    let found = cars.find(function (item) {
        return item.id === id;
    });

    if (found) {
        let targetIndex = cars.indexOf(found);
        console.log("Removed: id: " + cars[targetIndex].id + " | brand: " + cars[targetIndex].brand + " | model: " + cars[targetIndex].model + " | year: " + cars[targetIndex].year);
        cars.splice(targetIndex, 1);
    }
});

app.listen(8080);
console.log('Listening on port 8080');
<html>
    <head>

    </head>
    <body>
      <div id="obj"></div>
        
        <form method="POST" action="/car">
            id:
            <input type="text" name="id" />
            brand:
            <input type="text" name="brand" />
           model:
            <input type="text" name="model" />
            year:
            <input type="text" name="year" />
            <input type="submit"/>
          </form>
          
          <form method="POST" action="/car/:id">
            remove id:
            <input type="text" name="id" />
          
            <input type="submit" />
          </form>
    </body>
</html>

List is kept in memory. How am I supposed to display it on html web page now? I don't need anything too fancy for now, so I've been thinking about converting it to JSON and just displaying raw JSON file, but all solutions are made of actual ocean of code, and I doubt so much is needed for simply displaying JSON file.

Edit

Found the solution by accident.

app.get('/carlist', function (req, res) {
    res.send(cars);
});

0 Answers0