Kong / unirest-nodejs

Unirest in Node.js: Simplified, lightweight HTTP client library.
http://unirest.io/nodejs
MIT License
949 stars 167 forks source link

I keep getting status 400 #95

Closed slidenerd closed 8 years ago

slidenerd commented 8 years ago

I am trying to query Facebook Graph API. This is the actual format of the request capture

This code works perfectly using the request module capture

I am trying to convert from request to unirest. This doesn't work capture

Gives me an error status 400 every time. Am I missing something?

Go straight to the bottom of the page and check UPDATE 4

slidenerd commented 8 years ago

UPDATE 1

This is my response object when I am doing it through request module. This works perfectly and I think I may have narrowed down the source of the actual error. It all has to do with the messageData that is being attached as JSON. Unirest is not able to read it and pull a value from it called recipientID Check the bolded part for both updates

httpModule: { Server: [Object], createServer: [Function], globalAgent: [Object], Agent: [Object], request: [Function], get: [Function] }, agentClass: { [Function: Agent] super_: [Object] }, agent: Agent { domain: null, _events: [Object], _eventsCount: 1, _maxListeners: undefined, defaultPort: 443, protocol: 'https:', options: [Object], requests: {}, sockets: [Object], freeSockets: {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, maxCachedSessions: 100, _sessionCache: [Object] }, _started: true, href: 'https://graph.facebook.com/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', req: domain: null, _events: [Object], _eventsCount: 4, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Object], connection: [Object], _header: 'POST /v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD HTTP/1.1\r\nhost: graph.facebook.com\r\naccept: application/json\r\ncontent-type: application/json\r\ncontent-length: 241\r\nConnection: close\r\n\r\n', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, method: 'POST', path: '/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', parser: null, res: [Circular] }, ntick: true, response: [Circular], originalHost: 'graph.facebook.com', originalHostHeaderName: 'host', responseContent: [Circular], _destdata: true, _ended: true, callbackCalled: true }, toJSON: [Function: responseToJSON], caseless: Caseless { dict: { 'access-control-allow-origin': '', pragma: 'no-cache', 'cache-control': 'private, no-cache, no-store, must-revalidate', 'facebook-api-version': 'v2.7', expires: 'Sat, 01 Jan 2000 00:00:00 GMT', 'x-fb-trace-id': 'HLLEWdyLHOB', 'x-fb-rev': '2508223', vary: 'Accept-Encoding', 'x-fb-debug': '9GC++KqbE57CHQYEsq7sM1D1m/eWgWksg7zZNXjSyGGVbwDuXKCKoqv9/hXAITIL2eALrGkGqWtSP3i7Of4NOQ==', date: 'Tue, 16 Aug 2016 08:55:37 GMT', connection: 'close', read: [Function], *_body: { recipient_id: '1180278848689010', message_id: 'mid.1471337736988:080fa2424a0ffce140' } }**

slidenerd commented 8 years ago

UPDATE 2 I narrowed down the error further. It gives an oauth exception saying recipientID is missing. This is basically a property inside that javascript object called messageData and I am giving the same thing to both request and unirest. Request perfectly works whereas unirest throws this exception ultimately causing a 400 error. I have bolded the part at the bottom of the log that has the recipientID error. I believe I am sending the JSON data incorrectly, Any suggestions

IncomingMessage { _readableState: highWaterMark: 16384, buffer: [], ended: true, endEmitted: true, domain: null, _maxListeners: undefined, _tlsOptions: isServer: false, ALPNProtocols: undefined, requestOCSP: undefined }, secure: [Function], drain: [Function: ondrain], _eventsCount: 9, _connecting: false, _handle: null, _host: 'graph.facebook.com', _readableState: reading: true, sync: false, emittedReadable: false, readableListening: false, defaultEncoding: 'utf8', awaitDrain: 0, decoder: null, encoding: null }, readable: false, _writableState: WritableState { highWaterMark: 16384, needDrain: false, ending: true, ended: true, finished: true, 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: 0, prefinished: true, errorEmitted: false, corkedRequestsFree: [Object] }, writable: false, allowHalfOpen: false, destroyed: true, _bytesDispatched: 605, _sockname: null, _pendingData: null, _pendingEncoding: '', server: undefined, _server: null, ssl: null, _requestCert: true, parser: null, _httpMessage: ClientRequest { domain: null, _events: [Object], _eventsCount: 4, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Circular], connection: [Circular], _header: 'POST /v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD HTTP/1.1\r\nAccept: application/json\r\nContent-Type: application/json\r\nhost: graph.facebook.com\r\ncontent-length: 250\r\nConnection: close\r\n\r\n', _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, method: 'POST', path: '/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', parser: null, res: [Circular] }, read: [Function], _consuming: true, _idleNext: null, _idlePrev: null, _idleTimeout: -1 }, connection: TLSSocket { _tlsOptions: { pipe: null, secureContext: [Object], isServer: false, requestCert: true, rejectUnauthorized: true, session: <Buffer 30 82 08 05 02 01 01 02 02 03 03 04 02 c0 2b 04 20 66 53 85 25 57 14 61 ff 46 db ba 43 4d 10 eb b6 52 f3 93 d4 ad 0a ce d9 ff 9d 18 31 f5 93 c3 6b 04 ... >, ALPNProtocols: undefined, requestOCSP: undefined }, _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, _SNICallback: null, servername: null, npnProtocol: false, alpnProtocol: false, authorized: true, authorizationError: null, encrypted: true, _events: { close: [Object], end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], secure: [Function], free: [Function: onFree], agentRemove: [Function: onRemove], drain: [Function: ondrain], error: [Object] }, _eventsCount: 9, _connecting: false, _handle: null, _host: 'graph.facebook.com', _readableState: ReadableState { objectMode: false, highWaterMark: 16384, 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: false, domain: null, _maxListeners: 0, _writableState: WritableState { objectMode: false, highWaterMark: 16384, needDrain: false, ending: true, ended: true, finished: true, 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: 0, prefinished: true, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: false, server: undefined, _server: null, ssl: null, _requestCert: true, _rejectUnauthorized: true, parser: null, _httpMessage: ClientRequest { domain: null, _events: [Object], _eventsCount: 4, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Circular], connection: [Circular], _header: 'POST /v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD HTTP/1.1\r\nAccept: application/json\r\nContent-Type: application/json\r\nhost: graph.facebook.com\r\ncontent-length: 250\r\nConnection: close\r\n\r\n', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, method: 'POST', path: '/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', parser: null, res: [Circular] }, _consuming: true, _idleNext: null, _idlePrev: null, _idleTimeout: -1 }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: true, headers: { 'www-authenticate': 'OAuth "Facebook Platform" "invalidrequest" "(#100) The parameter recipient is required"', 'access-control-allow-origin': '', pragma: 'no-cache', 'cache-control': 'no-store', 'facebook-api-version': 'v2.7', expires: 'Sat, 01 Jan 2000 00:00:00 GMT', 'content-type': 'application/json', 'x-fb-trace-id': 'HYt8Adxebe8', 'x-fb-rev': '2507156', vary: 'Accept-Encoding', 'x-fb-debug': 'ChI66e2xhuqSUlIVrYeupZ4kr8gdJmm0cpINWy8erRwoxD062iqO12nd9+UXDJjskbB/fSGp9pfBbcmX2lgylg==', date: 'Tue, 16 Aug 2016 09:57:27 GMT', 'content-length': '128' }, rawHeaders: [ 'WWW-Authenticate', 'OAuth "Facebook Platform" "invalidrequest" "(#100) The parameter recipient is required"', 'Access-Control-Allow-Origin', '', 'Pragma', 'no-cache', 'Cache-Control', 'no-store', 'facebook-api-version', 'v2.7', 'Expires', 'Sat, 01 Jan 2000 00:00:00 GMT', 'Content-Type', 'application/json', 'x-fb-trace-id', 'HYt8Adxebe8', 'x-fb-rev', 'Accept-Encoding', 'X-FB-Debug', 'ChI66e2xhuqSUlIVrYeupZ4kr8gdJmm0cpINWy8erRwoxD062iqO12nd9+UXDJjskbB/fSGp9pfBbcmX2lgylg==', 'Date', 'Tue, 16 Aug 2016 09:57:27 GMT', 'Connection', 'close', 'Content-Length', '128' ], trailers: {}, rawTrailers: [], upgrade: false, url: '', method: null, statusCode: 400, statusMessage: 'Bad Request', client: TLSSocket { _tlsOptions: { pipe: null, isServer: false, requestCert: true, rejectUnauthorized: true, session: <Buffer 30 82 08 05 02 01 01 02 02 03 03 04 02 c0 2b 04 20 66 53 85 25 57 14 61 ff 46 db ba 43 4d 10 eb b6 52 f3 93 d4 ad 0a ce d9 ff 9d 18 31 f5 93 c3 6b 04 ... >, NPNProtocols: undefined, ALPNProtocols: undefined, requestOCSP: undefined }, _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, servername: null, npnProtocol: false, alpnProtocol: false, authorizationError: null, encrypted: true, { close: [Object], end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function: onFree], agentRemove: [Function: onRemove], drain: [Function: ondrain], error: [Object] }, _connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'graph.facebook.com', ReadableState { objectMode: false, highWaterMark: 16384, buffer: [], pipes: null, pipesCount: 0, flowing: true, readableListening: false, encoding: null }, readable: false, domain: null, _maxListeners: 0, _writableState: WritableState { ending: true, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, allowHalfOpen: false, _sockname: null, _pendingData: null, ssl: null, _events: [Object], _eventsCount: 4, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, chunkedEncoding: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Circular], connection: [Circular], _header: 'POST /v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD HTTP/1.1\r\nAccept: application/json\r\nContent-Type: application/json\r\nhost: graph.facebook.com\r\ncontent-length: 250\r\nConnection: close\r\n\r\n', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], method: 'POST', parser: null, read: [Function], _consuming: true, _consuming: true, req: ClientRequest { domain: null, drain: [Function] }, outputEncodings: [], outputSize: 0, _last: true, useChunkedEncodingByDefault: true, sendDate: false, _hasBody: true, finished: true, _headerSent: true, socket: TLSSocket { _tlsOptions: [Object], _controlReleased: true, authorized: true, _events: [Object], _eventsCount: 9, _connecting: false, _handle: null, _parent: null, _host: 'graph.facebook.com', readable: false, domain: null, writable: false, allowHalfOpen: false, destroyed: true, _pendingEncoding: '', _server: null, _requestCert: true, _rejectUnauthorized: true, read: [Function], _idlePrev: null, _idleTimeout: -1 }, connection: _tlsOptions: [Object], _secureEstablished: true, _securePending: false, authorizationError: null, _events: [Object], _eventsCount: 9, _host: 'graph.facebook.com', _readableState: [Object], _maxListeners: 0, _writableState: [Object], writable: false, _server: null, _requestCert: true, _rejectUnauthorized: true, parser: null, read: [Function], _idleTimeout: -1 }, _header: 'POST /v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD HTTP/1.1\r\nAccept: application/json\r\nContent-Type: application/json\r\nhost: graph.facebook.com\r\ncontent-length: 250\r\nConnection: close\r\n\r\n', _headerNames: _events: [Object], _eventsCount: 1, _maxListeners: undefined, freeSockets: {}, keepAliveMsecs: 1000, _sessionCache: [Object] }, socketPath: undefined, Request { domain: null, pipe: [Function], response: [Function: handleGZIPResponse], end: [Object], _maxListeners: undefined, headers: 'Content-Type': 'application/json', body: '{"json":{"recipient":{"id":"1180278848689010"},"message":{"text":"hi Vivek Ramesh, hope you are doing great! Can you send me your location so that I can tell you the weather? You can type the name of your city or tap the location pin shown below."}}}', writable: true, _qs: Querystring { useQuerystring: undefined, parseOptions: {}, stringifyOptions: {} }, Auth { request: [Circular], hasAuth: false, sentAuth: false, Multipart { request: [Circular], boundary: '3c7e01b8-edc8-4c3b-a0b4-406b875fba42', body: null }, _redirect: followRedirects: true, followAllRedirects: false, allowRedirect: [Function], maxRedirects: 10, redirects: [], redirectsFollowed: 0, removeRefererHeader: false }, _tunnel: setHeader: [Function], Url { protocol: 'https:', slashes: true, host: 'graph.facebook.com', port: 443, pathname: '/v2.7/me/messages', path: '/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', tunnel: true, originalCookieHeader: undefined, _disableCookies: true, _jar: undefined, host: 'graph.facebook.com', path: '/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', _json: true, httpModule: { Server: [Object], createServer: [Function], globalAgent: [Object], request: [Function], agent: _events: [Object], _maxListeners: undefined, protocol: 'https:', sockets: [Object], freeSockets: {}, maxFreeSockets: 256, _started: true, req: _events: [Object], _eventsCount: 4, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _hasBody: true, _trailer: '', connection: [Object], _header: 'POST /v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD HTTP/1.1\r\nAccept: application/json\r\nContent-Type: application/json\r\nhost: graph.facebook.com\r\ncontent-length: 250\r\nConnection: close\r\n\r\n', _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, method: 'POST', path: '/v2.7/me/messages?access_token=EAAPkF7dJlOkBAHf1fZCLBXZCXqodGyWLHsXgS1rZCcgIExHAlsXIbz76fMFZCLZAaDDzNeoZB3jfZCZAHDuk6353FKSjVAZDZD', parser: null, ntick: true, originalHost: 'graph.facebook.com', responseContent: [Circular], _destdata: true, _ended: true, dict: { 'www-authenticate': 'OAuth "Facebook Platform" "invalid_request" "(#100) The parameter recipient is required"', 'x-fb-trace-id': 'HYt8Adxebe8', 'x-fb-rev': '2507156', { error: fbtrace_id: 'HYt8Adxebe8' } }, code: 400, created: false, resetContent: false, partialContent: false, multiStatus: false, found: false, temporaryRedirect: false, permanentRedirect: false, forbidden: false, notAcceptable: false, requestTimeout: false, conflict: false, lengthRequired: false, requestEntityTooLarge: false, expectationFailed: false, misdirectedRequest: false, failedDependency: false, preconditionRequired: false, tooManyRequests: false, requestHeaderFieldsTooLarge: false, notImplemented: false, variantAlsoNegotiates: false, insufficientStorage: false, notExtended: false, cookies: {}, cookie: [Function], raw_body: { error: { message: '(#100) The parameter recipient is required', code: 100, fbtrace_id: 'HYt8Adxebe8' } } }

slidenerd commented 8 years ago

This is the actual body body: '{"json":{"recipient":{"id":"1180278848689010"},"message":{"text":"hi Vivek Ramesh, hope you are doing great! Can you send me your location so that I can tell you the weather? You can type the name of your city or tap the location pin shown below."}}}',

I still get the error however saying message: '(#100) The parameter recipient is required', code: 100

The code is modified to add the type as well capture

slidenerd commented 8 years ago

UPDATE 4

I further narrowed down the error There is a difference between the body for request and unirest REQUEST _body: { recipient_id: '1180278848689010', messageid: 'mid.1471337736988:080fa2424a0ffce140' } }*

UNIREST body: '{"json":{"recipient":{"id":"1180278848689010"},"message":{"text":"hi Vivek Ramesh, hope you are doing great! Can you send me your location so that I can tell you the weather? You can type the name of your city or tap the location pin shown below."}}}',

slidenerd commented 8 years ago

Update 5 I FIXED THE ERROR I was using json: messageData as key value pairs but it turns out I dont need that key lol, silly me capture