简体   繁体   English

使用click事件更改节点app.js全局变量

[英]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". 可以说我在app.js中创建了一个变量,如下所示: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?? 调用click事件时,如何更改我的app.locals.language =“ ES”?

all the languages im using in my application are html, css, javascript, jquery, node.js & express. 我在应用程序中使用的所有语言都是html,css,javascript,jquery,node.js和express。 thank you in advance 先感谢您

NodeJS is server side code, and your click would come from the client. NodeJS是服务器端代码,您的点击将来自客户端。 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. 所以,当你POST到具有可变的路线被称为'global'它会改变你的语言到任何被发送。 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} 您应该看到注销对象为{success: true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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