Basic Node and Express - Use the .env File

Basic Node and Express - Use the .env File
0

#1

Hi, my code works properly on the glitch page. but it returns the following error in FCC -:

The response of "/json" does not change according to MESSAGE_STYLE

My code

let messageObject = {"message": "Hello json"};

app.get('/json', function(req, res) {
  if (process.env.MESSAGE_STYLE === 'uppercase') {
     return res.json(messageObject.message.toUpperCase());
  } else {
      return res.json(messageObject.message);
  }
});

link for glitch app
https://veil-cereal.glitch.me/


Problem of Basic Node and Express - Use the .env File
#2

https://veil-cereal.glitch.me/json
returns
messageObject.toUpperCase is not a function

You sure messageObject.message is string type?


#3

i had changed the code a little… here is updated one

let messageObject = {"message": "Hello json"};

app.get('/json', function(req, res) {
  if (process.env.MESSAGE_STYLE === 'uppercase') {
     return res.json(messageObject.toUpperCase());
  } else {
      return res.json(messageObject);
  }
});

maybe because im trying to pass the to upper case function on an object the error comes


#4

I had tried doing it another way after reading similar questions here…

but im wondering if there is a way to solve it in this set of code, directly trying to apply the toUpperCase function inside the res.json()


#5

I’m sorry I thought messageObject is not included in your code provided, sorry.

Yes, how do you uppercase an object?!

I’m not sure how does res.json could create a json with just one string?

What about this?

let messageObject = {"message": "Hello json"};
app.get('/json', function(req, res) {
  if (process.env.MESSAGE_STYLE === 'uppercase') {
     var u_=JSON.parse(JSON.stringify(messageObject ));
     u_.message=u_.message.toUpperCase();
     return res.json(u_);
  } else {
      return res.json(messageObject);
  }
});

#6

thanks that works alright

can you explain this line, what is its use here
var u_=JSON.parse(JSON.stringify(messageObject ));


#7
JSON.stringify(<<json_obj>>)

turns the json object to string.

JSON.parse(<<str>>)

parse string and creates on json object.

JSON.parse(JSON.stringify(messageObject ));

means copy the messageObject object, but I think another better approach are out there, maybe u_={...messageObject } works too, don’t know ,have a try.

Keep going on great work, happy programming.


#8

app.get(’/json’,(req,res) => {
let jsonData = {“message”: “Hello json”};
if(process.env.MESSAGE_STYLE == “uppercase”) { jsonData.message = jsonData.message.toUpperCase() }
return res.json(jsonData);
}
);