Основи Node та Express - Використання .env-файлу

Розкажіть нам, що сталося:
Доброго дня, шановні колеги! Поясніть будь ласка послідовність виконання завдання.


Тобто, перше я працюю з використанням VS code, в корні я створив файл .env і записав туди зміну var MESSAGE_STYLE = “Hello World”.toUpperCase();

Після чого в myApp.js я вписую тільки умову виконання завдання if (process.env.MESSAGE_STYLE === “allCaps”) {
response = “Hello World”.toUpperCase();
} else {
response = “Hello World”;
}
або я її вписую в функцію? app.get(“/json”, function (req, res){
res.json({“message”: “Hello json”})

if (process.env.MESSAGE_STYLE === “allCaps”) {
response = “Hello World”.toUpperCase();
} else {
response = “Hello World”;
}});
Що не так я роблю, дякую!
Посилання на ваші проєкти
solution: http://localhost:3000

Інформація про ваш браузер:

Агент користувача: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

Завдання: Основи Node та Express - Використання .env-файлу

Посилання на завдання:

This logic needs to be inside the callback for your GET. Out here it cannot respond to changes in the environment variable.


Sorry, but nothing, not work!

I said that the logic needs to go inside of the GET; why did you comment out the GET? I’m not sure I understand?

Please post actual code instead of a picture.

Yes, I understud, but I’m not sure if I did the whole sequence correctly. And yet, or this import is correctly specified require(‘dotenv’).config(); and what is it for?


not work too

Please post actual code instead of a picture.


The instructions also don’t mention the environment variable value of "allCaps". You need to read and follow the instructions on what string to return and what environment variable value to check for. If you don’t use the values the instructions tell you to use, then it is impossible for you to pass this challenge.

require('dotenv').config();

let express = require('express');
let app = express();

// app.get("/", function(req, res) {
//     res.sendFile(__dirname + "/views/index.html");
//   });

//   app.use("/public", express.static(__dirname + "/public"));

  app.get("/json", function (req, res){
  //   res.json({"message": "Hello json"})  

  if (process.env.MESSAGE_STYLE === "allCaps") {
        response = "Hello World".toUpperCase();
      } else {
        response = "Hello World";
 }});

This is still not the environment variable from the instructions.

This is still not the message from the instructions.

I didn’t quite understand, that is “allCaps” , need to add instead “Hello World” (like is in the file .env), and instead of response = “Hello World” - response = “hello world”?

require(‘dotenv’).config();

let express = require(‘express’);
let app = express();

// app.get(“/”, function(req, res) {
// res.sendFile(__dirname + “/views/index.html”);
// });

// app.use(“/public”, express.static(__dirname + “/public”));

app.get(“/json”, function (req, res){
// res.json({“message”: “Hello json”})

if (process.env.MESSAGE_STYLE === “Hello World”) {
response = “Hello World”.toUpperCase();
} else {
response = “hello world”;
}});

You need to read the instructions

Створіть файл .env в основі каталогу вашого проєкту та збережіть в ньому змінну MESSAGE_STYLE=uppercase.

Then, in the /json GET route handler you created in the last challenge access process.env.MESSAGE_STYLE and transform the response object’s message to uppercase if the variable equals uppercase. Об’єкт відповіді має бути {"message": "Hello json"} або {"message": "HELLO JSON"}, в залежності від значення MESSAGE_STYLE.

Sorry, maybe I am stupid, but not understand nothing.
So, in the file .env , I have variable var MESSAGE_STYLE = uppercase;
Then in the /json GET route handler, I access process.env.MESSAGE_STYLE : app.get(“/json”, function (req, res){ };
Inside which we write the condition: if (process.env.VAR_NAME === ‘uppercase’) {
let response = “Hello World”.toUpperCase();
res.json({“message”: response})
}
else {
res.json({“message”: “Hello World”});
}
})

So the whole code looks like this:
let express = require(‘express’);
let app = express();

app.get(“/json”, function (req, res){
if (process.env.VAR_NAME === ‘uppercase’) {
let response = “Hello World”.toUpperCase();
res.json({“message”: response})
}
else {
res.json({“message”: “Hello World”});
}
})

do not confuse Linux with Javascript.
In Shell files, which .env is you should use such such shell syntax.

ENVIRONMENT_VARIABLE=whatever

# this is an error  cause it is javascript!!!
#var MESSAGE_STYLE = uppercase;

also you need to trace your code.
Add such a code to your js, to see if you see the value of the shell variable.

console.log("MESSAGE_STYLE:"+process.env.MESSAGE_STYLE);

you need to see in console that it is MESSAGE_STYLE:uppercase or the value you assigned.

AND last but the most important use markdown to write code.
This is how to write code.
example article

    ```javascript
    var code = "value"
    ```
    ```bash
    A_SHELL_VAR=value
    ```
    ```java
    String str = "value"
    ```

p.s(in ukrainian for clarification):
не плутайте Linux з Javascript.
У файлах оболонки, якими є .env, ви повинні використовувати синтаксис оболонки shell.

також вам потрібно трасувати свій код.
Додайте такий код до свого js, щоб побачити, чи бачите ви значення змінної оболонки.

І останнє, але найважливіше, використовуйте markdown для написання коду.
Ось як пиcати код в markdown.
3 зворотні галочки.

This is still the wrong string.

This isn’t correct now.

Thank you for helping, everybody! If somebody interesting, I am sending screen with correct code. And variability in the .env file.

Excellent, but you shouldn`t create ‘response’ variable