Home > Mobile >  Why can't I get "res" object console logged inside the callback of app.listen in node
Why can't I get "res" object console logged inside the callback of app.listen in node

Time:05-10

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?

CodePudding user response:

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.

CodePudding user response:

The listen() method allows you to link the server to a connection (host/port)
The callback is executed when connection added, not when receiving a request, it doesn't take req/res parameters

Take a loot at:
https://www.w3schools.com/nodejs/met_server_listen.asp
https://nodejs.org/api/net.html#serverlisten

  • Related