0

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}`));
1

2 Answers 2

1

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

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

Comments

0

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);  
  });

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.