A
A
asd dsa2018-11-12 18:33:05
JavaScript
asd dsa, 2018-11-12 18:33:05

Why am I not receiving data when following a route?

When I follow the '/gallery' route, I get the data from the 'posts.json' file. using the 'fs' module I use the 'read()' method to read the data. As a result, I download a data file when I go through the route, and I want to display them on the screen) Tell me what I'm doing wrong and how to implement it?
app.js:

const express = require('express');
const  Database =  require('./db');

const app = express();
const port = 3000;
const  db = new Database();

app.use(express.json());

app.get('/gallery', (req, res) => {
    db.read();
    res.send(db.pictures);
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}!`);
});

db.js:
class Database {

    constructor(){
        this.fs = require('fs');
        this.pictures = [];

    }

    read() {
        this.fs.readFile('./posts.json', (err, data)=> {
            if(err) {
                throw err;
            }else {
               this.pictures = data;
            }
        });
    }
}

module.exports = Database;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
atawerrus, 2018-11-12
@atawerrus

You are not passing the content, but the file, so it is downloaded, look at the read and fs method itself, it reads the data in a closure and does not return them anywhere, that is, you need to throw the fs module into your route and throw res into the closure and already do it inside res.send(data);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question