Node.js запрашивает документацию по объекту? [закрыто]

80

Это довольно простой вопрос, но я ничего не нашел в Google. Я ищу документацию по параметру запроса в функции создания сервера Node.js, но мне не удалось ничего найти.

http.createServer(function(request, response){
  console.log(JSON.stringify(request));
});

Отладка с помощью JSON.stringify () дает мне ошибку, что объект круговой, и программа останавливается. Я видел разные вещи, например request.url, или request.body, но есть ли страница, документирующая все функции и параметры запроса? Кажется, это должно быть легко найти, просто я не могу его найти.

Я попробовал еще раз, и оказалось, что просто console.log(request)выписываю все данные из запроса. Вот это просто ссылка:

ondata: [Function],
     _httpMessage:
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular] } },
  connection:
   { _connecting: false,
     _handle:
      { fd: null,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState:
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: 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: [Function: ondrain],
        timeout: [Function],
        error: [Function],
        close: [Object] },
     _maxListeners: 10,
     _writableState:
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [] },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     errorEmitted: false,
     bytesRead: 357,
     _bytesDispatched: 0,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 1,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:1337' },
     _idleTimeout: 120000,
     _idleNext:
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        msecs: 120000,
        ontimeout: [Function: listOnTimeout] },
     _idlePrev:
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        msecs: 120000,
        ontimeout: [Function: listOnTimeout] },
     _idleStart: 1371952289619,
     parser:
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _httpMessage:
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular] } },
  httpVersion: '1.1',
  complete: false,
  headers:
   { host: 'localhost:1337',
     connection: 'keep-alive',
     'cache-control': 'max-age=0',
     accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
     'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like
 Gecko) Chrome/27.0.1453.116 Safari/537.36',
     'accept-encoding': 'gzip,deflate,sdch',
     'accept-language': 'en-US,en;q=0.8,ja;q=0.6' },
  trailers: {},
  _pendings: [],
  _pendingIndex: 0,
  url: '/',
  method: 'GET',
  statusCode: null,
  client:
   { _connecting: false,
     _handle:
      { fd: null,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState:
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: 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: [Function: ondrain],
        timeout: [Function],
        error: [Function],
        close: [Object] },
     _maxListeners: 10,
     _writableState:
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [] },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     errorEmitted: false,
     bytesRead: 357,
     _bytesDispatched: 0,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 1,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:1337' },
     _idleTimeout: 120000,
     _idleNext:
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        msecs: 120000,
        ontimeout: [Function: listOnTimeout] },
     _idlePrev:
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        msecs: 120000,
        ontimeout: [Function: listOnTimeout] },
     _idleStart: 1371952289619,
     parser:
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _httpMessage:
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: false,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: true,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular] } },
  _consuming: false,
  _dumped: false,
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  upgrade: false }
Benjamin Collins
источник
54
You have my sympathy. Most modern languages, libraries, and frameworks have appalling reference documentation. If you visit the node documentation referred to below, you'll find that it's not actually a reference at all; it's more of a discussion. For example, the createServer() doc says that it takes as parameter "a function which is automatically added to the 'request' event" and returns "a web server object". There is no hint as to what 'type' either of these things is, and certainly no link to the reference doc for those things. What are they? F minus for the docs.
jarmod
1
I read through the question, and it seems pretty reasonable to me. The problem here is that it is the responses which have taken this from a question to a conversation / pity party on horrible documentation. If a reasonable answer/explanation could be given, I think this question is salvageable. Perhaps even a new, related question is best.
demongolem
I asked this question 6 years ago. Since then I've gotten a lot more experience with reading through the Nodejs documentation, and who ever works on the Nodejs documentation has done a tremendous job of keeping it up to date and accurate. I think this question has gotten a lot of attention because it's a simple question, but it shows that there is a lot of information available through console.log in case you're stuck on something.
Benjamin Collins

Ответы:

26

I'm not sure if this is a correct reply as it seems straightforward to me, but did you have a look at http://nodejs.org/api/http.html#http_http_incomingmessage?

Request is instance of the above object. By the way, if you really want to see what's inside that object with "brute force," you should not parse it, as it will not be a JSON string at all, but instead do something like:

for (i in request) {
  //Your code here
}

Hope it helps.

Delio
источник
Oops, I meant json.stringify, not json.parse. Went back to try the for(i in request) approach you mention and for some reason, just doing console.log(request) ended up working. I expected it to just say, [Object object]. Maybe it has a specific toString function for console? Thanks for the reply.
Benjamin Collins
5
Better yet, to see what's inside any object, use util.inspect(). Util is a core module; you can simply var util=require('util'); and the util.inspect(obj). A basic issue with JSON.stringify() is that it will complain if there are cyclic references.
Thalis K.
2
_readableState, readable, domain, _events, _maxListeners, socket, connection, httpVersion, complete, headers, trailers, _pendings, _pendingIndex, url, method, statusCode, client, _consuming, _dumped, httpVersionMajor, httpVersionMinor, upgrade, setTimeout, read, _read, destroy, _addHeaderLine, _dump, push, unshift, setEncoding, pipe, unpipe, on, addListener, resume, pause, wrap, setMaxListeners, emit, once, removeListener, removeAllListeners, listeners
CaffeineAddiction
10

Just to add on, as a relative newbie in Node.js, I find it confusing that each framework has its own implementation of a "request" object.

For example,

Express: http://expressjs.com/api.html#req.param

and

Hapi: http://spumko.github.io/resource/api/#request-object (just to note that the raw request object is still available in request.raw.req)

Some libraries assume the presence of Express' "req.param" method, and fail when used in non-Express projects.

shaunlim
источник
Thank you very much for sharing the express api option.
Muhammad Raihan Muhaimin
The spumko link is broken.
Charles Holbrow
The parse documentation is more complete than most: parse.com/docs/js/symbols/http.IncomingMessage.html
Charles Holbrow
that parse url is 404, fwiw
Jon Biz
Why would you ever use an http "framework"? Node.js does http natively.
B T
6

I agree with Delio, the Request object is of type IncomingMessage object, which is created by http.ClientRequest.

Frederick G. Sandalo
источник