Implement a Root-Level Request Level Middleware

Problem:
Root level logger middleware should be active

I looked at previous posts with the same issue and couldn’t figure out the solution. I already tried npm update --save

My code is the same as other users, and I put the route before the other routes. It does print to the console when I visit localhost:3000. What could be the issue?

var express = require('express');
require('dotenv').config();
var app = express();

app.use(function middleware(req, res, next) {
    var string= req.method+" "+req.path+" - "+req.ip;
    console.log(string);
    // console.log(req.method + " " + req.path + " - " + req.ip);
    next();
});

console.log("Hello World");

app.get('/', function(req, res) {
    //res.send('Hello Express');
    absolutePath = __dirname + '/views/index.html';
    res.sendFile(absolutePath);
});

app.use("/public", express.static(__dirname +"/public")); //serve asset files from the /public directory to the /public path

app.get('/json', function(req, res) {
    const mySecret = process.env['MESSAGE_STYLE']
    var response = "Hello json";
    if (mySecret === "uppercase") {
        res.json({"message": response.toUpperCase()})
    } 
    else { 
        res.json({"message": response});
    }
});
module.exports = app;
1 Like

Please include actual code instead of a picture of code. Thanks.

Sorry, edited the post to put code blocks

Is that all of your code? Your full code is important here.

Edited the post to include all the code. Thank you.

what happened to this line?

var bodyParser = require('body-parser');

I actually don’t remember that line being there, but I added it to the top. Same error on the terminal when I try to submit on freecodecamp though:

image

Your code from the initial post is passing for me.

Are you submitting http://www.localhost:3000 by chance? Because that isn’t right, it should just be http://localhost:3000

SHOOT!!! That was the problem all along lol!!! Thanks!!!

Why is the www not needed? Is it because it’s local?

The short answer is yes you do not need www with localhost.


Not 100% sure why it crashes. Technically, localhost should resolve to 127.0.0.1 (loopback). The error with getaddrinfo likely means it’s related to Node doing a resolve of the address. If you just enter http://www.localhost:3000/ in the browser it doesn’t crash the server but when the test hits that it does crash it. Like I said I’m not actually sure why it is crashing but it seems like it can’t resolve the address.

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