【问题标题】:Change the value of a json object in Node.js with process.env使用 process.env 更改 Node.js 中 json 对象的值
【发布时间】:2020-08-13 10:10:03
【问题描述】:

我正在学习 Node.js atm,并尝试根据某些参数更改应用请求的响应。例如,如果我将 MESSAGE_STYLE 设置为大写,我希望 json 对象中的(单个)键的值变为大写。但是我似乎无法更改对象。我没有将值作为字符串读取,因此 toUpperCase() 不起作用。

在阅读this article 之后,我尝试了 JSON.parse 和 JSON.dump,但这也不起作用(除非我做错了)。非常感谢您的帮助!

这行不通

process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){
var response = res.json({
  "message": "Hello json"
});

if(process.env.MESSAGE_STYLE==='uppercase'){
  response.message.toUpperCase();
  return response;
} else {
  return response;
  };
});

但确实如此

process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){

if(process.env.MESSAGE_STYLE==='uppercase'){
  res.json({
  "message": "HELLO JSON"
})
} else {
    res.json({
  "message": "Hello json"
})
  };
});

【问题讨论】:

    标签: javascript node.js json object


    【解决方案1】:

    您已分配 response 对象,但需要将其覆盖以获取您对 response.message 属性的最新更改。

    process.env.MESSAGE_STYLE='uppercase';
    
    app.get('/json', function(req, res){
    // Variable assignment as object
    var response = {
      "message": "Hello json"
    };
    
    if(process.env.MESSAGE_STYLE==='uppercase'){
      //Override message attribute value based on condition
      response.message = response.message.toUpperCase();  
    }
    
    return res.json(response);
    });
    

    【讨论】:

    • 谢谢!实际上,我已经尝试使用 equals 运算符分配一个新值,但没有想过之后返回 res.json(尽管是一个简单的步骤)。有时显而易见的事情会直接溜走..
    • 在某些情况下会发生。最良好的祝愿。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2018-12-14
    • 2021-04-16
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多