2017-04-26 64 views
1

我對使用express-bunyan-logger的問題做了short, self contained example使用express-bunyan-logger和graphql記錄查詢字符串

我試圖添加express-bunyan-logger作爲中間件,並利用includesFn將查詢字符串和正文記錄爲自定義字段。

const app = express(); 

const graphqlLogger = require('express-bunyan-logger')({ 
    name: 'graphql-logger', 
    includesFn: (req, res) => { 
    const includes = {}; 
    if (req.body) includes.req_body = JSON.stringify(req.body); 
    if (req.query) includes.req_query = JSON.stringify(req.query); 
    return includes; 
    }, 
}); 

app.use(graphqlLogger); 

問題是,即使是形式http://localhost:4000/graphql?query=query%20%7B%0A%20%20books%20%7B%0A%20%20%20%20title%0A%20%20%7D%0A%7D的URL,該req_queryreq_body領域始終是空的。如果我檢查在調試器中傳遞給includesFnreq對象,它不包含req.query或req.params的任何值。

我確定我在這裏做錯了事;如何讓includesFn正確記錄查詢字符串和正文?

回答

1

所以,結果是includesFn被調用兩次,每個請求一次。

首先,對於GET請求,那麼只會得到req.query對象不爲空。

第二個請求是POST請求正在與JSON數據,所以爲了得到req.body定義,而不是空的,你必須做到以下幾點:

  1. 運行npm install body-parser
  2. 包括在app.js文件中的以下內容:

    const bodyParser = require('body-parser'); 
    
    ... 
    
    app.use(bodyParser.urlencoded({ 
        extended: true 
    })); 
    
    app.use(bodyParser.json());