Node.js - 如何检查请求数据?

Posted

技术标签:

【中文标题】Node.js - 如何检查请求数据?【英文标题】:Node.js - how to inspect request data? 【发布时间】:2017-09-25 23:09:24 【问题描述】:

我有一个 Node.js 路由,它发回一些文本并记录请求:

app.post('/registerUser', function (req, res) 
  res.send('Hello World post!')
  console.log(req);
)

然后我用 curl 击中那条路线,如下所示:

curl --data "username==test&foo==bar" http://localhost:3000/registerUser

这就是我通过节点得到的:

IncomingMessage 
  _readableState:
   ReadableState 
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList  head: null, tail: null, length: 0 ,
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: true,
     decoder: null,
     encoding: null ,
  readable: true,
  domain: null,
  _events: ,
  _eventsCount: 0,
  _maxListeners: undefined,
  socket:
   Socket 
     connecting: false,
     _hadError: false,
     _handle:
      TCP 
        bytesRead: 183,
        _externalStream: ,
        fd: 14,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 ,
     _parent: null,
     _host: null,
     _readableState:
      ReadableState 
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null ,
     readable: true,
     domain: null,
     _events:
       end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function: socketOnError],
        close: [Object],
        data: [Function: socketOnData],
        resume: [Function: onSocketResume],
        pause: [Function: onSocketPause] ,
     _eventsCount: 10,
     _maxListeners: undefined,
     _writableState:
      WritableState 
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 3,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] ,
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     _bytesDispatched: 222,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      Server 
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::3000' ,
     _server:
      Server 
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::3000' ,
     _idleTimeout: 120000,
     _idleNext:
      TimersList 
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: [Object],
        _unrefed: true,
        msecs: 120000 ,
     _idlePrev:
      TimersList 
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: [Object],
        _unrefed: true,
        msecs: 120000 ,
     _idleStart: 144720,
     parser:
      HTTPParser 
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': [Function: onParserExecute],
        _headers: [],
        _url: '',
        _consumed: true,
        socket: [Circular],
        incoming: [Circular],
        outgoing: null,
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] ,
     on: [Function: socketOnWrap],
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage:
      ServerResponse 
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: false,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _removedHeader: [Object],
        _contentLength: 17,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'HTTP/1.1 200 OK\r\nX-Powered-By: Express\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 17\r\nETag: W/"11-5i2g3OJs8No9M8PUhnLubxYJmZY"\r\nDate: Fri, 28 Apr 2017 00:06:49 GMT\r\nConnection: keep-alive\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: [Function: updateOutgoingData],
        req: [Circular],
        locals: ,
        statusMessage: 'OK',
        statusCode: 200  ,
  connection:
   Socket 
     connecting: false,
     _hadError: false,
     _handle:
      TCP 
        bytesRead: 183,
        _externalStream: ,
        fd: 14,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 ,
     _parent: null,
     _host: null,
     _readableState:
      ReadableState 
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null ,
     readable: true,
     domain: null,
     _events:
       end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function: socketOnError],
        close: [Object],
        data: [Function: socketOnData],
        resume: [Function: onSocketResume],
        pause: [Function: onSocketPause] ,
     _eventsCount: 10,
     _maxListeners: undefined,
     _writableState:
      WritableState 
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 3,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] ,
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     _bytesDispatched: 222,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      Server 
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::3000' ,
     _server:
      Server 
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::3000' ,
     _idleTimeout: 120000,
     _idleNext:
      TimersList 
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: [Object],
        _unrefed: true,
        msecs: 120000 ,
     _idlePrev:
      TimersList 
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: [Object],
        _unrefed: true,
        msecs: 120000 ,
     _idleStart: 144720,
     parser:
      HTTPParser 
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': [Function: onParserExecute],
        _headers: [],
        _url: '',
        _consumed: true,
        socket: [Circular],
        incoming: [Circular],
        outgoing: null,
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] ,
     on: [Function: socketOnWrap],
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage:
      ServerResponse 
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: false,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _removedHeader: [Object],
        _contentLength: 17,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'HTTP/1.1 200 OK\r\nX-Powered-By: Express\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 17\r\nETag: W/"11-5i2g3OJs8No9M8PUhnLubxYJmZY"\r\nDate: Fri, 28 Apr 2017 00:06:49 GMT\r\nConnection: keep-alive\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: [Function: updateOutgoingData],
        req: [Circular],
        locals: ,
        statusMessage: 'OK',
        statusCode: 200  ,
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  httpVersion: '1.1',
  complete: false,
  headers:
    host: 'localhost:3000',
     'user-agent': 'curl/7.43.0',
     accept: '*/*',
     'content-length': '23',
     'content-type': 'application/x-www-form-urlencoded' ,
  rawHeaders:
   [ 'Host',
     'localhost:3000',
     'User-Agent',
     'curl/7.43.0',
     'Accept',
     '*/*',
     'Content-Length',
     '23',
     'Content-Type',
     'application/x-www-form-urlencoded' ],
  trailers: ,
  rawTrailers: [],
  upgrade: false,
  url: '/registerUser',
  method: 'POST',
  statusCode: null,
  statusMessage: null,
  client:
   Socket 
     connecting: false,
     _hadError: false,
     _handle:
      TCP 
        bytesRead: 183,
        _externalStream: ,
        fd: 14,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 ,
     _parent: null,
     _host: null,
     _readableState:
      ReadableState 
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null ,
     readable: true,
     domain: null,
     _events:
       end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function: socketOnError],
        close: [Object],
        data: [Function: socketOnData],
        resume: [Function: onSocketResume],
        pause: [Function: onSocketPause] ,
     _eventsCount: 10,
     _maxListeners: undefined,
     _writableState:
      WritableState 
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 3,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] ,
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     _bytesDispatched: 222,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      Server 
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::3000' ,
     _server:
      Server 
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _connections: 1,
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _pendingResponseData: 0,
        _connectionKey: '6::::3000' ,
     _idleTimeout: 120000,
     _idleNext:
      TimersList 
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: [Object],
        _unrefed: true,
        msecs: 120000 ,
     _idlePrev:
      TimersList 
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: [Object],
        _unrefed: true,
        msecs: 120000 ,
     _idleStart: 144720,
     parser:
      HTTPParser 
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': [Function: onParserExecute],
        _headers: [],
        _url: '',
        _consumed: true,
        socket: [Circular],
        incoming: [Circular],
        outgoing: null,
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] ,
     on: [Function: socketOnWrap],
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage:
      ServerResponse 
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: false,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _removedHeader: [Object],
        _contentLength: 17,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'HTTP/1.1 200 OK\r\nX-Powered-By: Express\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 17\r\nETag: W/"11-5i2g3OJs8No9M8PUhnLubxYJmZY"\r\nDate: Fri, 28 Apr 2017 00:06:49 GMT\r\nConnection: keep-alive\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: [Function: updateOutgoingData],
        req: [Circular],
        locals: ,
        statusMessage: 'OK',
        statusCode: 200  ,
  _consuming: false,
  _dumped: false,
  next: [Function: next],
  baseUrl: '',
  originalUrl: '/registerUser',
  _parsedUrl:
   Url 
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: null,
     pathname: '/registerUser',
     path: '/registerUser',
     href: '/registerUser',
     _raw: '/registerUser' ,
  params: ,
  query: ,
  res:
   ServerResponse 
     domain: null,
     _events:  finish: [Function: resOnFinish] ,
     _eventsCount: 1,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: false,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: true,
     useChunkedEncodingByDefault: true,
     sendDate: true,
     _removedHeader:  'content-length': false ,
     _contentLength: 17,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      Socket 
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 10,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        _bytesDispatched: 222,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 144720,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] ,
     connection:
      Socket 
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 10,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        _bytesDispatched: 222,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 144720,
        parser: [Object],
        on: [Function: socketOnWrap],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] ,
     _header: 'HTTP/1.1 200 OK\r\nX-Powered-By: Express\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 17\r\nETag: W/"11-5i2g3OJs8No9M8PUhnLubxYJmZY"\r\nDate: Fri, 28 Apr 2017 00:06:49 GMT\r\nConnection: keep-alive\r\n\r\n',
     _headers:
       'x-powered-by': 'Express',
        'content-type': 'text/html; charset=utf-8',
        'content-length': '17',
        etag: 'W/"11-5i2g3OJs8No9M8PUhnLubxYJmZY"' ,
     _headerNames:
       'x-powered-by': 'X-Powered-By',
        'content-type': 'Content-Type',
        'content-length': 'Content-Length',
        etag: 'ETag' ,
     _onPendingData: [Function: updateOutgoingData],
     req: [Circular],
     locals: ,
     statusMessage: 'OK',
     statusCode: 200 ,
  route:
   Route 
     path: '/registerUser',
     stack: [ [Object] ],
     methods:  post: true   

问题是我的username==testfoo=bar 去哪儿了?如何访问req.data 或类似的东西?

我现在正在查看文档:https://nodejs.org/api/http.html#http_class_http_incomingmessage,这没有任何意义,我在请求中传递的数据没有一个字,我关心的一切都是我的数据,这就是我正在工作的on,这就是我要推送到 MongoDB 的内容。

我错过了一些大事。帮助? :)

【问题讨论】:

继续阅读该页面。当您到达 "message.url" 时,请格外注意。有一个完整、详细的解释,以及一个你正在尝试做什么的例子...... 还有一件事我忘了提到@Wordpressor,一旦你得到正文,只需使用 req.body.email 或任何名称将其推送到数据库 ***.com/questions/34028851/… 【参考方案1】:

如果您使用 express,那么如果您打印请求,简单请求将不会提供您想要的数据。

req.body 包含在请求正文中提交的数据键值对。默认情况下,它是未定义的,并在您使用 body-parser 和 multer 等正文解析中间件时填充。

这是文档中提到并由 Express Framework https://expressjs.com/en/api.html 推荐的内容

所以如果你想在 express 中检查它,可以这样做

var app = 

require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded( extended: true )); // for parsing application/x-www-form-urlencoded

app.post('/registerUser', function (req, res) 
  console.log(req.body); //console.log(req)
  res.json(req.body); //res.send("hello world post")
);

您也可以在不使用 express 框架或正文解析器的情况下检查您的请求。 在这里我只是发布一个简单的例子来打印每个请求的帖子正文

var http =

 require("http");

http.createServer(function (request, response) 
     request.on('data', function(chunk) 
        var bodydata = chunk.toString('utf8');
        console.log(bodydata)
    );
   response.writeHead(200, 'Content-Type': 'text/plain');
   response.end('hi welcome\n');
).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');

如果你使用 bodyparser 和 express 会是什么样子

here is body is you use body parser and express

这是我的发帖请求

这是我将缓冲区转换为字符串的输出

这是我的简单节点请求,不使用包含数据事件的 express

数据作为req中的缓冲区

【讨论】:

【参考方案2】:

这基本上就是 Express 的工作方式:

var express = require('express'),
    bodyparser = require('body-parser');

var app = express();

// Middleware
app.use(bodyparser.urlencoded(extended: false));

app.get('/foo', function (req, res) 
  // GET /foo?msg=hello ---> msg: 'hello'
  console.log(req.query);
);

app.post('/bar', function (req, res) 
  // POST msg=hello ---> msg: 'hello'
  console.log(req.body);
);

app.listen(3000);

【讨论】:

【参考方案3】:

如果传入的请求是GET,那么您可以通过req.query 访问它,并且这是开箱即用的 express。如果传入请求是POST,您需要使用this 之类的内容,然后您可以通过访问req.body 来访问传入信息。

【讨论】:

以上是关于Node.js - 如何检查请求数据?的主要内容,如果未能解决你的问题,请参考以下文章

Node.js Buffer(缓冲区)

Node.js log4j-like 日志系统

我无法弄清楚如何防止在 Node.js 中出现此 CORS 错误 [重复]

node.js操作数据库之MongoDB+mongoose篇

角度如何与 Ionic 应用程序中的节点一起工作?

[译]How to Install Node.js on Ubuntu 14.04 如何在ubuntu14.04上安装node.js