如何将所有 HTTP 请求记录到我的 Sails.js 服务器

How to log all HTTP requests to my Sails.js server?

本文关键字:我的 Sails js 服务器 记录 请求 HTTP      更新时间:2023-09-26

正如标题所说,如何将所有请求记录到我的 Sails.js 服务器? 我的日志配置中是否需要更改某些内容? 我只想查看发送到我的服务器的每个 GET、POST 等的列表。

您可能希望使用 middlewhere 表示。

查看 config/http.js(sails 10.5),他们有一个注释掉的例子。

如果由于某种原因您的帆版本没有该示例,则这里有一个 pastebin http://pastebin.com/xhUdFY2Z

否则,这些也应该有所帮助。

Node.js : 如何在 Express 中的所有 HTTP 请求上做一些事情?https://github.com/expressjs/morgan

For Sails v1.x,

您可以在 config/http.js 文件中实现中间件。

module.exports.http = {
middleware: {
  // default given middleware is commented by me just for concentrating on example
  // you should enable needed middlewares always
  order: [
    // 'cookieParser',
    // 'session',
    // 'bodyParser',
    // 'compress',
    // 'poweredBy',
    // 'router',
    // 'www',
    // 'favicon',
    'foobar'
  ],
  foobar: (function() {
    return function(req, res, next) {
      // here you will be having access to the Request object "req"
      let requestUrl = req.url
      let requestIpAddress = req.ip
      let requestMethod = req.method
      let requestHeader = req.header
      let requestBody = req.body
      // Now before going to return next(), you can call service and give above parameters to store in to Database or log in console.
      return next()
    }
  })(),
}}

此中间件的调用顺序与它在订单数组中的调用顺序相同。