Use the .env file

Hello everybody,
I’ve been stuck on this, and I’m getting frustrated about it.
myApp.js:

#step 1
app.get('/', function(req, res) {
    res.send("Hello Express");
})

#step 2
app.get('/', function(req, res) {
let path = __dirname + "/views/index.html"
res.sendFile(path)
})

#step 3
let path = __dirname + "/public";
app.use("/public", express.static(path))

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

#step 5
var helloObjLow = {"message": "Hello json"};
var helloObjUp = {"message": "HELLO JSON"};
app.get('/json', function(req, res) {
const mySecret = process.env['MESSAGE_STYLE']
if(mySecret == "uppercase") {
res.json(helloObjUp);
} else {
res.json(helloObjLow);
}
});

#step 6
var response = "Hello World".toUpperCase(); // now becomes "HELLO WORLD"
if (process.env.VAR_NAME === "allCaps") {
    response = "Hello World".toUpperCase();
  } else {
    response = "Hello World";
  }

Step 6 is the current step I’m on. Please respond simply and ASAP.

You should not use var at all. It’s a very old way to declare variables.

That code as written probably doesn’t do what you think. That logic for creating a response shouldn’t be floating around outside of a function, if I recall correctly. What is the link to the step?

Here’s the link to the step:

And here’s my new code:

#step 1
app.get('/', function(req, res) {
    res.send("Hello Express");
})

#step 2 
app.get('/', function(req, res) {
let path = __dirname + "/views/index.html"
res.sendFile(path)
})

#step 3
let path = __dirname + "/public";
app.use("/public", express.static(path))

#step 4
 let helloObj = {"message": "Hello json"};
 app.get('/json', function(req, res) {
 	res.json(helloObj);
 });

#step 5
let helloObjLow = {"message": "Hello json"};
let helloObjUp = {"message": "HELLO JSON"};
app.get('/json', function(req, res) {
const mySecret = process.env['MESSAGE_STYLE']
if(mySecret == "uppercase") {
res.json(helloObjUp);
} else {
res.json(helloObjLow);
}
});

#step 6
function formatResponse(letName) {
  let response;
  if (letName === "allCaps") {
    response = "Hello World".toUpperCase();
  } else {
    response = "Hello World";
  }
  return response;
}

The function’s still a work in progress, being that I made it in 9 minutes.

I don’t see where you’re using this function?

Note - it would help if you used consistent standard formatting in your code.

That’s what I was working on; trying to find a spot for it.

At the top of your myApp.js file, add require('dotenv').config() to load the environment variables.

Did you use the dotenv package as required?

No, I don’t think I added it. I’m going to try and add it now.

I keep getting these kinds of errors,

TypeError: Router.use() requires a middleware function but got a Object
    at Function.use (/workspace/boilerplate-express/node_modules/express/lib/router/index.js:469:13)
    at Function.<anonymous> (/workspace/boilerplate-express/node_modules/express/lib/application.js:227:21)
    at Array.forEach (<anonymous>)
    at Function.use (/workspace/boilerplate-express/node_modules/express/lib/application.js:224:7)
    at Object.setupBackgroundApp (/workspace/boilerplate-express/node_modules/fcc-express-bground/index.js:162:9)
    at Object.<anonymous> (/workspace/boilerplate-express/server.js:25:9)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Object..js (node:internal/modules/cjs/loader:1689:10)
    at Module.load (node:internal/modules/cjs/loader:1318:32)
    at Function._load (node:internal/modules/cjs/loader:1128:12)
node:events:496
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1907:16)
    at listenInCluster (node:net:1964:12)
    at Server.listen (node:net:2066:7)
    at Function.listen (/workspace/boilerplate-express/node_modules/express/lib/application.js:635:24)
    at Object.<anonymous> (/workspace/boilerplate-express/server.js:25:51)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Object..js (node:internal/modules/cjs/loader:1689:10)
    at Module.load (node:internal/modules/cjs/loader:1318:32)
    at Function._load (node:internal/modules/cjs/loader:1128:12)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1943:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 3000
}

What do they mean?
myApp.js:

// Load environment variables at the very beginning of your app
require('dotenv').config();

const express = require('express');
const app = express();
const path = require('path');

// Step 1
app.get('/', function(req, res) {
    res.send("Hello Express");
});

// Step 2 
app.get('/another-route', function(req, res) {
    let filePath = path.join(__dirname, "/views/index.html");
    res.sendFile(filePath);
});

// Step 3
let publicPath = path.join(__dirname, "/public");
app.use("/public", express.static(publicPath));

// Step 4
let helloObj = { "message": "Hello json" };
app.get('/json-default', function(req, res) {
    res.json(helloObj);
});

// Step 5 (updated)
app.get('/json', function(req, res) {
    // Now using process.env directly, which is populated by dotenv
    const mySecret = process.env.MESSAGE_STYLE;
    
    // Call the formatResponse function
    const responseMessage = formatResponse(mySecret);
    
    // Respond with the formatted message
    res.json({ "message": responseMessage });
});

// Function definition
function formatResponse(letName) {
    if (letName === "uppercase") {
        return "Hello json".toUpperCase();
    } else {
        return "Hello json";
    }
}

// Start the server
const server = app.listen(3000)
  .on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
      console.log('Port 3000 in use, trying another...');
      server.listen(0);
    } else {
      console.error(err);
    }
  });

Made it more understandable.

did you add this part in which step?
where is the export that was at the end of the file?

Oh… I must’ve accidentally deleted it. Let me add it back.

All right, here’s my code now:

// Load environment variables at the very beginning of your app
require('dotenv').config();

const express = require('express');
const app = express();
const path = require('path');

// Step 1
app.get('/', function(req, res) {
    res.send("Hello Express");
});

// Step 2 
app.get('/another-route', function(req, res) {
    let filePath = path.join(__dirname, "/views/index.html");
    res.sendFile(filePath);
});

// Step 3
let publicPath = path.join(__dirname, "/public");
app.use("/public", express.static(publicPath));

// Step 4
let helloObj = { "message": "Hello json" };
app.get('/json-default', function(req, res) {
    res.json(helloObj);
});

// Step 5 (updated)
app.get('/json', function(req, res) {
    // Now using process.env directly, which is populated by dotenv
    const mySecret = process.env.MESSAGE_STYLE;
    
    // Call the formatResponse function
    const responseMessage = formatResponse(mySecret);
    
    // Respond with the formatted message
    res.json({ "message": responseMessage });
});

// Function definition
function formatResponse(letName) {
    if (letName === "uppercase") {
        return "Hello json".toUpperCase();
    } else {
        return "Hello json";
    }
}

// Start the server
const server = app.listen(3000)
  .on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
      console.log('Port 3000 in use, trying another...');
      server.listen(0);
    } else {
      console.error(err);
    }
  });
  module.exports = app;

It means you tried to start the server when it was already running.

Seeing this is related to the test package, it is likely as explained the missing export there was in the starting code that you removed.

what about this part? you did not answer

I was trying to add it into this step.

why? this step still asks only about the /json endpoint

I was trying to make it cooperate with the /json endpoint, but I’m guessing it didn’t work out.

It may be causing more issues
You may want to do the thing of changing the start script so you don’t need to stop and restart the server everytime, if you forget to stop the server, you can’t start it. At this time it looks like you have port 3000 occupied, you need to kill the process you have there

server.js starts the server, not myApp.js it is just exporting the app. Do not start the server in myApp.js

server.js

const myApp = require('./myApp');

const port = process.env.PORT || 3000;
bGround.setupBackgroundApp(app, myApp, __dirname).listen(port, () => {
  bGround.log(`Node is listening on port ${port}...`);
});

So your saying I have to put it back to port? Or maybe I’m getting it backwards?

It’s two separate things.
You need remove server from myApp.js, and if you made changes to server.js you need to restore it.

Then if you need to start the server and you get an error that the port is already in use, you need to kill the process on port 3000