6

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! I served server and index.html on the same URL :) Now I have another problem but I think I can fix it by myself. Also thank you for correcting my English(it is not my native:))).
@Alexx awesome! no worries, I corrected + added formatting so that it is easier to read in case someone has the same question and comes here from google later. welcome to stackoverflow!
2

You can create a server that can communicate using REST API

(Assuming data is a string)

client:

let data = getSomeDataYouWantToSend()
fetch('/send', {
    method: 'POST',
    headers: {
      'Content-Type': 'text/plain'
    },
    body: data
})

Assuming you have static files in /main directory and html files in /views directory

server:

let express = require('express')
let app = express()

app.use(express.static(`${__dirname}/main`))
app.set('views', `${__dirname}/views`)

app.get('/', (req, res) => {
    res.render('index.html')
})

app.post('/send', (req, res) => {
    console.log(req.body) // <- here is your data sent from client frontend
})

app.listen(3000)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.