Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Why can't I get "res" object console logged inside the callback of app.listen in node.js
const http = require('http') 
const server = http.createServer(()=>{
            console.log("created server")
        });
const port = 3000;
server.listen(port, (req,res) => {console.log(res)})

// in console => undefined

//after opening the page => in console => created server

// no res obj in console

why can't "res" be consolelogged even after "created server" is console logged and "http://localhost:3000" is opened too?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

why can't "res" be consolelogged even after "created server" is console logged

The callback to server.listen() just tells you when your server has been started. It is not passed req or res as there is no active incoming http connection at the moment your server has just started.

req and res get passed to listeners for the request event which you can register for either by passing a callback to http.createServer() as in:

const server = http.createServer((req, res) => {
    console.log(res);
    res.end("hello");
});

Or, by registering a listener for the request event as in:

server.on('request', (req, res) => {
    console.log(res);
    res.end("hello");
});

So, it appears in your code that you just have the callbacks to http.createServer() and server.listen() reversed. It's the one to http.createServer() that is called with req and res, not the callback to server.listen(). That callback to server.listen() tells you when the server has been successfully started. The callback to http.createServer() tells you when an incoming http request has arrived and it passes req and res to that callback.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!