I am trying to send an object with data from a Node.js server to js file (for using this data in frontend).
In the file main.js I am manipulating the DOM. I do the following request:
let dataName = [];
let request = async ('http://localhost:3000/') => {
const response = await fetch(url);
const data = await response.json();
dataName = data.name;
}
let name = document.getElementById('name');
name.textContent = dataName;
Then in the file server.js I have an object:
data = [
{
"id": 1,
"name": "Jhon"
},
{
"id": 2,
"name": "Mike"
}
];
And I would like to send it as json string (or another way) to main.js as response for my request.
Problem: My data is displayed on window in browser. How could I get it as response?
I tried
let express = require('express');
let app = express();
app.use(express.static(`main`));
app.get('/', function(req, res){
res.json(data); //also tried to do it through .send, but there data only on window in browser
});
app.listen(3000);
Could someone tell me what to change in my code or point me in the direction in which to google? (I don't want to use template engines).
Help me pls :) Peace be with you.