Basic Node and Express - Chain Middleware to Create a Time Server

Tell us what’s happening:
Describe your issue in detail here.
I do not understand the reason why this does not work.

require('dotenv').config()
let express = require('express');
let app = express();
let absolutePath=__dirname + "/views/index.html"

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

app.use(express.static(__dirname + "/public"))
app.get("/",(req,res)=>{
  res.sendFile(absolutePath)
})

app.get("/json",(req,res) => {
  if(process.env.MESSAGE_STYLE === "uppercase"){
    res.json({ "message": "HELLO JSON" })
  }
    res.json({"message":"Hello json" })
   
});

app.get('/json', (req, res) => {
  process.env.MESSAGE_STYLE === 'uppercase' ? 
    res.json({ "message": "HELLO JSON" }):
    res.json({ "message": "Hello json" })
})

app.get("/now",function(req,res,next){
  req.time = new Date().toString();
  next();
},function(req,res){
        res.json(time:req.time); 
});
  




Your project link(s)

solution: boilerplate-express-2 - Node.js Repl - Replit

Your browser information:

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

Challenge: Basic Node and Express - Chain Middleware to Create a Time Server

Link to the challenge:

Hello,

I guess the issue is with this line :

app.get("/now",function(req,res,next){
  req.time = new Date().toString();
  next();
},function(req,res){
        res.json(time:req.time); 
});

next() enables you to go to the next middleware (I think, if I am wrong please someone correct it), but there isn’t any. You should put the 2nd function in a new middleware.

But regarding what is done in the first, try to do this :

app.get("/now",function(req,res,next){
  req.time = new Date().toString();
  res.json({ time: req.time });
});

Or only res.json(req.time), according to the format you want to get

1 Like