GeorgeMenezes
GeorgeMenezes

Reputation: 93

Sending data from Javascript to Node.js

I am trying to create a very basic function,

suppose my javascript data is const data = 1234;

how do i send this data to a node server i created using express framework

const express = require("express");
const app = new express();

app.get("/", (req, res) => {
    res.send("home");
});

app.post("/datastream", function (req, res) {
    res.send('You sent the data: "' + req.body.data + '".');
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`server started on port ${PORT}`));

Upvotes: 0

Views: 960

Answers (2)

Arek C.
Arek C.

Reputation: 1581

If you want to send it from browser and your server is running locally:

const data = 1234
fetch('http://localhost:5000/datastream', {
  method: 'POST',
  body: JSON.stringify({ data }),
  headers: { 'Content-Type': 'application/json' }
})
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(err => console.log(err))

Now you need to install body-parser middleware to be able to deserialize your JSON data npm install body-parser and attach it to your app. Add this to your server code:

const bodyParser = require('body-parser')
// ...
app.use(bodyParser.json())

If everything went good (your server is running on specified port) then it should log You sent the data: 1234. after you run your browser code

Upvotes: 1

Mik
Mik

Reputation: 385

You can send data from client to server using fetch method (very basic example):

const data = 1234;
fetch('/datastream', {
    method:"POST", 
    body: JSON.stringify({data: data})
  }).then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  })
  .catch(function(err) {  
    console.log('Fetch Error :' + err);  
  });

Upvotes: 0

Related Questions