Asked 6 years ago
17 Nov 2017
Views 963
angeo

angeo posted

how to log all http request at Node JS ?

I am using node js with electron js and i want log of http request made by request module

suppose

 request('google.com', function (error, response, html) {
       if (!error && response.statusCode == 200) {
}

})
ajamil

ajamil
answered Apr 24 '23 00:00

To log all HTTP requests in a Node.js application, you can use a middleware function to intercept incoming requests and log their details. Here's an example of how to do this using the built-in http module:



const http = require('http')

const server = http.createServer((req, res) => {
  // Log the request method and URL
  console.log(`${req.method} ${req.url}`)

  // Continue handling the request
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('Hello World!')
})

server.listen(3000, () => {
  console.log('Server started on port 3000')
})

In the example above, a new http server is created using http .createServer(). A function is passed to this method that will be called every time a new HTTP request is received. The function logs the request method and URL using console.log() and continues handling the request by sending a response.

When you run your Node.js server with this configuration, all HTTP requests will be logged to the console.

You can also customize the log format and destination by modifying the logging function in the middleware.
Post Answer