Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

928
Vistas
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.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

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)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda