Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data from node.js to frontend using pure js

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.

like image 731
Alexx Avatar asked Mar 21 '20 14:03

Alexx


1 Answers

I think you are trying to serve your frontend and the JSON data on the same URL /.

You need to adjust your server code as follows:

let express = require('express');
let app = express();
app.use(express.static(`main`));
app.get('/api', function(req, res){
    res.json(data); //also tried to do it through .send, but there data only on window in browser
});
app.listen(3000);

Now your data will be available as JSON from /api. Then you can make a request on the frontend as follows:

let dataName = [];
let request = async () => {
    const response = await fetch('http://localhost:3000/api');
    const data = await response.json();
    dataName = data.name;
}

let name = document.getElementById('name');
name.textContent = dataName;

There was also an issue with the url not being defined properly as an argument. I adjusted the function to simply use the URL string in the right place.

like image 186
omnidan Avatar answered Oct 01 '22 03:10

omnidan