Home > Enterprise >  How to send data from React to Node?
How to send data from React to Node?

Time:03-02

I am really new to node and wanted to know how to send some data from my frontend using react to my backend (Node JS).I want to send some string to my backend,is this the process or is it a completely different thing?

 useEffect(() => {
        fetch("/api")
          .then((res) => res.json())
          .then((data) => setData(data.message));
      }, []);

index.js file

// server/index.js

const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

app.get("/api", (req, res) => {
  const tmp=req.body;
    res.json({ message: tmp });
  });

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

CodePudding user response:

Your /api route is listening to GET requests. GET requests can't contain body, therefore you won't be receiving anything inside the body.

If you want to pass data with get request, you can either use query parameters or URL parameters. Passing query params would be something like,

fetch('/api?'   new URLSearchParams({
    message: 'message',
}))

To receive this from backend and use it as a response, you can access the query parameters like below using req.query,

app.get('/api', function(req, res) {
  res.json({
    message: req.query.message
  });
});

You can also send data using URL parameters with GET request, instead of using query parameters.

I suggest taking a deeper look at HTTP requests.

CodePudding user response:

you need to use post method, here is the client side using fetch api(from mdn docs):

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

and for backend, you can handle it this way (from express docs):

const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();

//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

router.post(‘/handle’,(request,response) => {
//code to perform particular action.
//To access POST variable use req.body()methods.
const {answer} = request.body;
res.json({answer});
});

// add router in the Express app.
app.use("/", router);
  • Related