Json request with .env code problem

Tell us what’s happening:
Why this code does not work?


const mySecret = process.env['MESSAGE_STYLE']

app.get('/json',(req,res) => {
if(mySecret === "uppercase") {
  res.json({
  message: "HELLO JSON"
  });
}
else{
  res.json({
  message: "Hello json"
  });
}
  
});

Your project link(s)

solution: https://replit.com/@anilatasoyy/boilerplate-express-3

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36

Challenge: Use the .env File

Link to the challenge:

1 Like

My problem is solved when I change mySecret to process.env.MESSAGE_STYLE but I think it is problematic since you insert it as mySecret in built in replit function

It works because you move the check inside the get route. Not because of how you are accessing it.

Edit: Just to be clear, this would work as well:

app.get('/json', (req, res) => {
  const mySecret = process.env['MESSAGE_STYLE']
  if (mySecret === "uppercase") {
    res.json({
      message: "HELLO JSON"
    });
  }
  else {
    res.json({
      message: "Hello json"
    });
  }
});
1 Like

thanks for the alternative though I still don’t understand why mySecret outside get request didn’t worked shouldn’t it be in a bigger scope while outside?

I was having the same problems as well… Thank you for the solution. For me though, I only managed to pass it because I forgot the golden rule of refreshing the page and running it again. Or maybe it was because I was using Google Chrome (latest version)?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.