send variable data from node js to front end javascript
- In your Node.js server, use the
express
framework to create a route that handles the request from the front end.
const express = require('express');
const app = express();
const port = 3000;
app.get('/getData', (req, res) => {
// Your data logic here
const dataToSend = "Hello from Node.js!";
res.send({ data: dataToSend });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
- In your front-end JavaScript file, use an HTTP request library like
axios
or the nativefetch
API to send a request to the Node.js server and receive the data.
// Using axios
const axios = require('axios');
axios.get('http://localhost:3000/getData')
.then(response => {
// Handle the data received from the server
const data = response.data.data;
console.log(data);
})
.catch(error => {
// Handle errors
console.error('Error fetching data:', error);
});
OR
// Using native fetch API
fetch('http://localhost:3000/getData')
.then(response => response.json())
.then(data => {
// Handle the data received from the server
console.log(data.data);
})
.catch(error => {
// Handle errors
console.error('Error fetching data:', error);
});
- Run your Node.js server by executing the script in your terminal:
node your-server-file.js
- Open your HTML file in a browser and check the browser console for the output from the server.
Note: Make sure to install the required packages by running:
npm install express axios
Replace the data logic in the server route (/getData
) with your actual data retrieval or generation logic.