简体   繁体   中英

change node app.js global variable with click event

lets say i created a variable in my app.js like this: app.locals.language = "EN". now, we have user using my website that clicked a dropdown menu to change the pages language to, lets say, spanish. how can i go about in changing my app.locals.language = "ES" when the click event is called??

all the languages im using in my application are html, css, javascript, jquery, node.js & express. thank you in advance

NodeJS is server side code, and your click would come from the client. So you'd need some way of talking to the server from the client. One way you could do it would be to create a route in express that when posted to, changes the environment variable. It would look something like this:

app.post('/change', (req, res) => {
  const newVar = req.body.global;
  app.locals.language = newVar;
  res.json({
    success: true
  });
});

So when you POST to the route with a variable called 'global' it will change your language to whatever was sent. From the client, you would do something like this:

<button onClick="changeGlobal('EN')">Change Global To EN</button>
<button onClick="changeGlobal('ES')">Change Global To ES</button>

function changeGlobal(language) {
  fetch('/change', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify({global: language})
  })
  .then(res=>res.json())
  .then(res => console.log(res));
}

You should see a log out with an object of {success: true}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM