Search code examples
javascriptnode.jsexpressserverclient

How do i send an updated variable from client to server with fetch?


I am trying to send a changed variable from the client to the server, but i cant figure it out. What i am trying to achiveve is that i can use it in the main.ejs.

<script>
document.getElementById("char2btn").addEventListener("click", change)
function change() {
  charOneInView = "Yes"
  const data = {charOneInView}
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  };
  
  fetch('/welcome2', options)
}
  </script>

Index.js:

var  charoptioneOne = "No"

router.post('/welcome2',  ensureAuthenticated, function(req, res){
   console.log(req.body)
   res.redirect('/main'); 
  })
  
router.get('/main', ensureAuthenticated, (req, res) =>
  res.render('main',  {
    user: req.user,
    charOneInView: charoptioneOne,
    charTwoInView: charoptioneTwo
  })
)

To me it looks like its still a object and not a changed variable, how do i fix this?


Solution

  • use body-parser module in backend

    const bodyParser = require("body-parser");
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    

    set header of request like this:

      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }