Search code examples
javascriptnode.jsreactjsexpressmern

How to send a variable from react to node


I'm a beginner, and I'm trying to figure out how to send a variable generated from a function in react to the backend server side.

The user clicks on a button and a json object called rowObject is generated in home.jsx . I want to send it to backend to post.js to save it to the database. How do I achieve this?


Solution

  • Your front end would make a request to your server, perhaps with something like the browsers built in fetch() function.

    For example:

    function MyComponent() {
      function onClick() {
        fetch(
          '/some/path/here',
          {
            method: 'POST',
            body: JSON.stringify({ myData: 123 })
          }
        )
      }
    
      return <div onClick={onClick}>Click Me</div>
    }
    

    Then on the backend in express you would have something like:

    const express = require('express')
    const app = express()
    const port = 3000
    
    app.post('/some/path/here', (req, res) => {
      dbOrSomething.saveSomewhere(req.body) // your implementation here
      res.send('Saved!')
    })
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`)
    })