How to pass a JSON to the Express front end

Asked

Viewed 30 times

0

Hello! I was wondering if there’s any way I can get a JSON file to the Front End using Express...

I’m using this method:

app.use(express.static(__dirname + '/public'));

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html")
})

And, I want to know how to send a . JSON to the front end... In case, it would "receive" using normal Javascript...

Heed I don’t want to use any library or Framework. Only Express.

1 answer

0

To load the contents of the JSON file to the server synchronously:

var fs = require('fs');
app.use(express.static('public'))
app.use(express.json());
var jsonData = JSON.parse(fs.readFileSync('meuArquivo.json', 'utf8'));

Then to display on the screen:

app.get("/", (req, res) => {
    res.status(200).json(jsonData);
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.