Related
I'm currently playing with the google places api to gain some comfort level with it, but I've come up on an issue that has me a little stumped and I'm hoping someone can course correct me here. I'm making api calls to a local proxy server, and so far everything is working except when I try to pull an image for a specific business.
I've gone so far as to console log each individual part of the get request url to ensure it's correctly concatenated and everything appears correct in that regard (I'm able to paste it straight into the browser and get the expected result). I have a hunch this is a general code issue and not something specific to places api itself, but any insight into this would be greatly appreciated.
Error in terminal from proxy server (doesn't seem terribly useful, but someone else might recognize something here that I'm not):
undefined:1 ���� ^
SyntaxError: Unexpected token � in JSON at position 0
Front end code:
function makeAPICall(url) {
return fetch(url);
}
makeAPICall(`http://localhost:5000/places/${searchString}`)
.then(response => {
return response.json();
})
.then(data => {
responseObject = data.results;
renderResult(responseObject[10]);
return responseObject[10];
})
.then(responseObject => {
makeAPICall(`http://localhost:5000/place/image/${responseObject.photos[0].photo_reference}`)
.then(response => {
return response.json();
})
.then(photoData => {
console.log(photoData);
});
});
Proxy code (minus the working routes not relevant to the issue):
require('dotenv').config({path: '../.env'});
const express = require('express');
const request = require('request');
const GOOGLE_API_KEY = process.env.API_KEY;
const placesImgURL = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=';
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/place/image/:query', (req, res) => {
request(
{ url: `${placesImgURL}${req.params.query}&key=${GOOGLE_API_KEY}` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
console.log(response);
}
res.json(JSON.parse(body));
}
)
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
UPDATE:
The line in the server code where the error is triggered is:
res.json(JSON.parse(body));
Screenshot of network call from within dev tools:
When console logging the line that's throwing an error, I get the following (fair warning, this is the full log and it's extremely long):
ServerResponse {
_events: { finish: [Function: bound resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 22631,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
onread: [Function: onStreamRead],
onconnection: null,
_consumed: true,
[Symbol(owner)]: [Circular] },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
emitClose: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
_events:
{ end: [Array],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 8,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: true,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 3,
prefinished: false,
errorEmitted: false,
emitClose: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::5000',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 5 },
_server:
Server {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::5000',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 5 },
timeout: 120000,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [IncomingMessage],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 8,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 6746,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 9,
[Symbol(triggerId)]: 8 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
onread: [Function: onStreamRead],
onconnection: null,
_consumed: true,
[Symbol(owner)]: [Circular] },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
emitClose: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
_events:
{ end: [Array],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 8,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: true,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 3,
prefinished: false,
errorEmitted: false,
emitClose: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::5000',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 5 },
_server:
Server {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::5000',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 5 },
timeout: 120000,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [IncomingMessage],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 8,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 6746,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 9,
[Symbol(triggerId)]: 8 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 },
_header:
'HTTP/1.1 200 OK\r\nX-Powered-By: Express\r\nAccess-Control-Allow-Origin: *\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 22631\r\nETag: W/"5867-c3Fodr1eSCA3vlKX+kDMgudDONQ"\r\nDate: Wed, 26 Aug 2020 18:14:27 GMT\r\nConnection: keep-alive\r\n\r\n',
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req:
IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: true,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: true,
readableListening: false,
resumeScheduled: false,
emitClose: true,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: true,
decoder: null,
encoding: null },
readable: true,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
socket:
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 8,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 6746,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 9,
[Symbol(triggerId)]: 8 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 8,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 6746,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 9,
[Symbol(triggerId)]: 8 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ host: 'localhost:5000',
connection: 'keep-alive',
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
accept: '*/*',
origin: 'http://localhost:3000',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'if-none-match': 'W/"5868-+iRV2Q1kdgam9TbgiDgKID9Vs1s"' },
rawHeaders:
[ 'Host',
'localhost:5000',
'Connection',
'keep-alive',
'User-Agent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
'Accept',
'*/*',
'Origin',
'http://localhost:3000',
'Sec-Fetch-Site',
'same-site',
'Sec-Fetch-Mode',
'cors',
'Sec-Fetch-Dest',
'empty',
'Referer',
'http://localhost:3000/',
'Accept-Encoding',
'gzip, deflate, br',
'Accept-Language',
'en-US,en;q=0.9',
'If-None-Match',
'W/"5868-+iRV2Q1kdgam9TbgiDgKID9Vs1s"' ],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '/places/restaurants+near%20me',
method: 'GET',
statusCode: null,
statusMessage: null,
client:
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
timeout: 120000,
parser: [HTTPParser],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 8,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: 120000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 6746,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 9,
[Symbol(triggerId)]: 8 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 },
_consuming: false,
_dumped: false,
next: [Function: next],
baseUrl: '',
originalUrl: '/places/restaurants+near%20me',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/places/restaurants+near%20me',
path: '/places/restaurants+near%20me',
href: '/places/restaurants+near%20me',
_raw: '/places/restaurants+near%20me' },
params: { query: 'restaurants+near me' },
query: {},
res: [Circular],
route:
Route { path: '/places/:query', stack: [Array], methods: [Object] } },
locals: {},
statusMessage: 'OK',
statusCode: 200,
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
{ 'x-powered-by': [ 'X-Powered-By', 'Express' ],
'access-control-allow-origin': [ 'Access-Control-Allow-Origin', '*' ],
'content-type': [ 'Content-Type', 'application/json; charset=utf-8' ],
'content-length': [ 'Content-Length', '22631' ],
etag: [ 'ETag', 'W/"5867-c3Fodr1eSCA3vlKX+kDMgudDONQ"' ] } }
_http_outgoing.js:470
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/Users/tyleranyan/Documents/api-practice/places/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/tyleranyan/Documents/api-practice/places/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/tyleranyan/Documents/api-practice/places/node_modules/express/lib/response.js:267:15)
at Request.request [as _callback] (/Users/tyleranyan/Documents/api-practice/places/proxy/server.js:25:11)
at Request.self.callback (/Users/tyleranyan/Documents/api-practice/places/node_modules/request/request.js:185:22)
at Request.emit (events.js:182:13)
at Request.<anonymous> (/Users/tyleranyan/Documents/api-practice/places/node_modules/request/request.js:1154:10)
at Request.emit (events.js:182:13)
at IncomingMessage.<anonymous> (/Users/tyleranyan/Documents/api-practice/places/node_modules/request/request.js:1076:12)
The problem here is that the request library appears to have been deprecated. If you switch to another one such as axios, the following code based on your own works without problem:
const express = require('express')
const axios = require('axios')
const url = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=YOUR_API_KEY"
const getData = async (url) => {
try {
const response = await axios.get(url)
const data = response.data
console.log('data', response.data)
} catch (error) {
console.log('error', error)
}
}
const app = express()
const port = 3000
app.get('/', async (req, res) => {
res.send(await getData(url))
})
app.listen(port, () => {})
Output:
Response GET / status=200
"data"
"����\u0000\u0010JFIF\u0000\u0001\u00…01b`J+]�Ǥ�%�„c����8�\u001fb\u0017/��..."
Also the response is an image; don't json it in the backend. There's the client-side service though.
New to this so this may be a silly question. Testing out a Node.js server and socket.io. Trying to figure out what the constant
request /inform
requests coming to my server are.
Is this a browser thing? Socket thing? I'm not calling for it in my site to my knowledge...
UPDATE: disabled socket.io on server and client and the requests are still coming.
Thanks!
The request continues to come even with browser closed. Changing the port stops the request...
Here is the server (more of a learning experience than a ready for production thing) AND the full logged request after.
//EXAMPLE server without any outside frameworks ie. "Express"
//Require modules
var http = require('http'); //heart of node, handles http requests and responses
var fs = require('fs'); //read and write to file system
var path = require('path'); // used to extract extension from url path
var server = http.createServer(function (request, response) { //creating the server
console.log('request ', request.url); //logs the requested url
var filePath = './public' + request.url; // adds default path plus requested path
if (filePath == './public/')
filePath = './public/index.html'; //if path is left blank, returns homepage
//The HTTP 'Content Type' header field must be correct to return css, image, and other static files
//the following takes care of that
var extname = String(path.extname(filePath)).toLowerCase(); //extract extension convert to lower case string
var contentType = 'text/html'; //default contentType to be sent back
var mimeTypes = { //maps extention to type
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.svg': 'application/image/svg+xml'
};
contentType = mimeTypes[extname] || 'application/octet-stream'; //set contentType to corresponding value
//Content Type is now defined based on request
//Now we serve the file
fs.readFile(filePath, function(error, content) { //invokes fs module to read file at filepath
if (error) { //calls funtion to throw errors or send content as a response
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType }); //here's where the contentType comes into play
response.end(content, 'utf-8');
}
});
}).listen(8080); //activates server
console.log('Server running port 8080');
/*var io = require('socket.io')(server);
var newShotCount = 0;
io.on('connection', function(socket){
console.log('a user connected');
setInterval (function() {
io.emit('count changed', newShotCount.toString());
console.log(newShotCount.toString());
newShotCount += 1;
},4000)
}); */
request 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,
destroyed: false,
defaultEncoding: 'utf8',
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 {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_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,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Array],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_bytesDispatched: 0,
_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,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8080',
[Symbol(asyncId)]: 6 },
_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,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8080',
[Symbol(asyncId)]: 6 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 4742,
_destroyed: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage:
ServerResponse {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
[Symbol(outHeadersKey)]: null },
[Symbol(asyncId)]: 9,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 11,
[Symbol(triggerAsyncId)]: 9 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_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,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Array],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_bytesDispatched: 0,
_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,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8080',
[Symbol(asyncId)]: 6 },
_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,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8080',
[Symbol(asyncId)]: 6 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 4742,
_destroyed: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage:
ServerResponse {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
[Symbol(outHeadersKey)]: null },
[Symbol(asyncId)]: 9,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 11,
[Symbol(triggerAsyncId)]: 9 },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: false,
headers:
{ host: '192.168.1.31',
connection: 'Close',
'user-agent': 'AirControl Agent v1.0',
'content-type': 'application/x-binary',
'content-length': '3960' },
rawHeaders:
[ 'Host',
'192.168.1.31',
'Connection',
'Close',
'User-Agent',
'AirControl Agent v1.0',
'Content-Type',
'application/x-binary',
'Content-Length',
'3960' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/inform',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_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,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Array],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_bytesDispatched: 0,
_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,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8080',
[Symbol(asyncId)]: 6 },
_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,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8080',
[Symbol(asyncId)]: 6 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 4742,
_destroyed: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage:
ServerResponse {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
[Symbol(outHeadersKey)]: null },
[Symbol(asyncId)]: 9,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 11,
[Symbol(triggerAsyncId)]: 9 },
_consuming: false,
_dumped: false }
Well it was coming from my local network... Several UniFi aps around and apparently they were broadcasting and polling
My NodeJS server is attempting to be able to use and store a file that it gets via a POST request, but I can't figure out how to access the file being passed to it via the req variable. It looks like the post itself is both being executed and has some data in the request, but I need to access that POST file as a variable, how do I do this?
My code:
Node:
...
app.post('/imgUpload', function(req, res) {
console.log(req);
}
React:
...
class RyanForm extends React.Component {
send() {
const method = "POST";
const body = new FormData(this.form);
console.log('sending info: ' + body);
axios.post(URLs.imgUpload, body, { headers: { 'Content-Type': 'multipart/form-data' } })
}
render() {
return (
<div>
<h1>I'm a form.</h1>
<form ref={el => (this.form = el)}>
<label>file:</label>
<input type="file" name="im-a-file" />
</form>
<button onClick={() => this.send()}>Send</button>
<p>Submit me to see what I send to the server.</p>
</div>
);
}
}
(Node) Server log:
We have a compiled contract!
Cuzzo's app running on port 8003!
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: 492,
_externalStream: {},
fd: 14,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_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: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_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::::8003' },
_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::::8003' },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 17023,
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: {},
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_headers: [Object],
_headerNames: [Object],
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: {} } },
connection:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
bytesRead: 492,
_externalStream: {},
fd: 14,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_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: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_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::::8003' },
_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::::8003' },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 17023,
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: {},
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_headers: [Object],
_headerNames: [Object],
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: {} } },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: false,
headers:
{ host: '127.0.0.1:8003',
connection: 'keep-alive',
'content-length': '89231',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:3000',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryGl0P9Dl4n16OT4aK',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9' },
rawHeaders:
[ 'Host',
'127.0.0.1:8003',
'Connection',
'keep-alive',
'Content-Length',
'89231',
'Accept',
'application/json, text/plain, */*',
'Origin',
'http://localhost:3000',
'User-Agent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36',
'Content-Type',
'multipart/form-data; boundary=----WebKitFormBoundaryGl0P9Dl4n16OT4aK',
'Referer',
'http://localhost:3000/',
'Accept-Encoding',
'gzip, deflate, br',
'Accept-Language',
'en-US,en;q=0.9' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/imgUpload',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
bytesRead: 492,
_externalStream: {},
fd: 14,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_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: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
destroyed: false,
_bytesDispatched: 0,
_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::::8003' },
_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::::8003' },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 17023,
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: {},
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_headers: [Object],
_headerNames: [Object],
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: {} } },
_consuming: false,
_dumped: false,
next: [Function: next],
baseUrl: '',
originalUrl: '/imgUpload',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/imgUpload',
path: '/imgUpload',
href: '/imgUpload',
_raw: '/imgUpload' },
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: {},
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
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: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 17023,
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: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 17023,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] },
_header: null,
_headers:
{ 'x-powered-by': 'Express',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Origin, X-Requested-With, Content-Type, Accept' },
_headerNames:
{ 'x-powered-by': 'X-Powered-By',
'access-control-allow-origin': 'Access-Control-Allow-Origin',
'access-control-allow-headers': 'Access-Control-Allow-Headers' },
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: {} },
route:
Route {
path: '/imgUpload',
stack: [ [Object] ],
methods: { post: true } } }
NPM Packages (Node):
var express = require('express')
var fs = require('fs');
var http = require('http');
var bigInt = require("big-integer");
var fs = require('fs');
var cmd = require('node-cmd');
var qs = require('querystring');
var util = require('util');
const fileUpload = require('express-fileupload');
var app = express();
Send data to server as enctype="multipart/form-data". In server side use multer module.
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
var fileDest = path.join('../uploads/');
if (!fs.existsSync(fileDest)) {
mkdirp(fileDest, function(err) {
if (err) {
logger.error(err);
callback(err, false);
} else {
callback(null, '../uploads/');
}
});
} else {
callback(null, '../uploads/');
}
},
filename: function(req, file, callback) {
callback(null, file.fieldname + '.' + file.originalname.split('.')[1]);
}
});
var upload = multer({
storage: storage,
fileFilter: function(req, file, callback) {
// To reject this file pass `false`, like so:
var sw = 0;
for (var i = 0; i < config.validMimeTypes.length; i++) {
if (file.mimetype === config.validMimeTypes[i]) {
sw = 1;
break;
}
}
if (sw === 0) {
logger.error('Not allowed file type sent');
// return callback(new Error('Only video files are allowed!'));
return callback('Only ... files are allowed!', false);
}
// To accept the file pass `true`, like so:
callback(null, true);
},
limits: {
fileSize: config.maxUploadSize
}
});
app.post('/upload', upload.any(), router.uploader);
I've just started to fiddle with three new (to me) frameworks/products: MongoDB, NodeJS and AngularJS.
What I'm trying to accomplish is to have a simple form submit a value and have that value written to the database. I've gotten to a point where my value is submitted using $http.post in my Angular app and I do get my node.js backend function called but my req parameter (se below) in undefined. From Google Chromes Network monitor I can see that a POST request is submitted and that the payload contains the value I've entered.
I really don't understand why it's not available in the receiving end. Please help.
Now for some snippets (not the entire files):
server.js:
var express = require('express'),
menu = require('./routes/menu'),
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser');
app.use(bodyParser.json());
app.set('port', 3000);
app.use(express.static(__dirname));
app.get('/menuItems', menu.getMenuItems);
app.post('/menuItems', function(req, res) { console.log(req); });
httpServer.listen(app.get('port'), function () {
console.log("Express server listening on port %s.", httpServer.address().port);
});
menu.js:
exports.addMenuItem = function(req, res) {
var menuItem = req.body; <===req.body is undefined
console.log('Adding menuItem: ' + JSON.stringify(menuItem));
db.collection('menuItems', function(err, collection) {
collection.insert(menuItem, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
app.js:
(function () {
var app = angular.module('jdk', []);
app.controller('MenuItemController', function ($scope, $http) {
$scope.processForm = function () {
$http.post('/menuItems', JSON.stringify($scope.formData))
.success(function (data) {
console.log(data);
});
};
});
})();
I think I've dome everything but apparently not. I also tried installing and using 'body-paarser' in my server.js but the result was the same.
When my server crashes it dumps something like this:
{ _readableState:
{ highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: false,
ended: false,
endEmitted: false,
reading: false,
calledRead: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
objectMode: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
oldMode: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_maxListeners: 10,
socket:
{ _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,
oldMode: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Object],
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: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 2496,
_bytesDispatched: 157759,
_pendingData: null,
_pendingEncoding: '',
server:
{ domain: null,
_events: [Object],
_maxListeners: 10,
_connections: 6,
connections: [Getter/Setter],
_handle: [Object],
_usingSlaves: false,
_slaves: [],
allowHalfOpen: true,
httpAllowHalfOpen: false,
timeout: 120000,
_connectionKey: '4:0.0.0.0:3000' },
_idleTimeout: 120000,
_idleNext:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 375,
_bytesDispatched: 1410,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Circular],
_idleStart: 1406644394348,
parser: [Object],
ondata: [Function],
_paused: false,
_httpMessage: null },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
_idleStart: 1406644399010,
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],
_paused: false,
_httpMessage:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_headerSent: false,
_header: '',
_hasBody: true,
_trailer: '',
finished: false,
_hangupClose: false,
socket: [Circular],
connection: [Circular],
_headers: [Object],
_headerNames: [Object],
req: [Circular],
locals: {} } },
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,
oldMode: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Object],
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: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 2496,
_bytesDispatched: 157759,
_pendingData: null,
_pendingEncoding: '',
server:
{ domain: null,
_events: [Object],
_maxListeners: 10,
_connections: 6,
connections: [Getter/Setter],
_handle: [Object],
_usingSlaves: false,
_slaves: [],
allowHalfOpen: true,
httpAllowHalfOpen: false,
timeout: 120000,
_connectionKey: '4:0.0.0.0:3000' },
_idleTimeout: 120000,
_idleNext:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 375,
_bytesDispatched: 1410,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Circular],
_idleStart: 1406644394348,
parser: [Object],
ondata: [Function],
_paused: false,
_httpMessage: null },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
_idleStart: 1406644399010,
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],
_paused: false,
_httpMessage:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_headerSent: false,
_header: '',
_hasBody: true,
_trailer: '',
finished: false,
_hangupClose: false,
socket: [Circular],
connection: [Circular],
_headers: [Object],
_headerNames: [Object],
req: [Circular],
locals: {} } },
httpVersion: '1.1',
complete: false,
headers:
{ host: 'localhost:3000',
connection: 'keep-alive',
'content-length': '19',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:3000',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
'content-type': 'application/json;charset=UTF-8',
referer: 'http://localhost:3000/admin/',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'en,da;q=0.8,nb;q=0.6,sv;q=0.4' },
trailers: {},
_pendings: [],
_pendingIndex: 0,
url: '/menuItems',
method: 'POST',
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,
oldMode: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Object],
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: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 2496,
_bytesDispatched: 157759,
_pendingData: null,
_pendingEncoding: '',
server:
{ domain: null,
_events: [Object],
_maxListeners: 10,
_connections: 6,
connections: [Getter/Setter],
_handle: [Object],
_usingSlaves: false,
_slaves: [],
allowHalfOpen: true,
httpAllowHalfOpen: false,
timeout: 120000,
_connectionKey: '4:0.0.0.0:3000' },
_idleTimeout: 120000,
_idleNext:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 375,
_bytesDispatched: 1410,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Circular],
_idleStart: 1406644394348,
parser: [Object],
ondata: [Function],
_paused: false,
_httpMessage: null },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
_idleStart: 1406644399010,
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],
_paused: false,
_httpMessage:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_headerSent: false,
_header: '',
_hasBody: true,
_trailer: '',
finished: false,
_hangupClose: false,
socket: [Circular],
connection: [Circular],
_headers: [Object],
_headerNames: [Object],
req: [Circular],
locals: {} } },
_consuming: false,
_dumped: false,
httpVersionMajor: 1,
httpVersionMinor: 1,
upgrade: false,
next: [Function: next],
baseUrl: '',
originalUrl: '/menuItems',
_parsedUrl:
{ protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/menuItems',
path: '/menuItems',
href: '/menuItems' },
params: {},
query: {},
res:
{ domain: null,
_events: { finish: [Function] },
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_headerSent: false,
_header: '',
_hasBody: true,
_trailer: '',
finished: false,
_hangupClose: false,
socket:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 2496,
_bytesDispatched: 157759,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 1406644399010,
parser: [Object],
ondata: [Function],
_paused: false,
_httpMessage: [Circular] },
connection:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
onend: [Function],
destroyed: false,
bytesRead: 2496,
_bytesDispatched: 157759,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 1406644399010,
parser: [Object],
ondata: [Function],
_paused: false,
_httpMessage: [Circular] },
_headers: { 'x-powered-by': 'Express' },
_headerNames: { 'x-powered-by': 'X-Powered-By' },
req: [Circular],
locals: {} },
route:
{ path: '/menuItems',
stack: [ [Object] ],
methods: { post: true } } }
you need to use the https://www.npmjs.org/package/body-parser module to parse the body of POST request.
app.use(express.static(__dirname));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/menuItems', menu.getMenuItems);
I have a small server and small client. The code has been extrapolated to focus on the problem at hand.
I have a client that sends a POST request to the server. The server responds with a json object. I am unable to see the json response object from within the node.js client. However, if I make a curl request, I can see it...
//SERVER
var restify = require('restify'),
Logger = require('bunyan'),
api = require('./routes/api'),
util = require('util'),
fs = require('fs');
//START SERVER
var server = restify.createServer({ name: 'image-server', log: log })
server.listen(7000, function () {
console.log('%s listening at %s', server.name, server.url)
})
server.use(restify.fullResponse());
server.use(restify.bodyParser());
//change from github
var user = {username: "usr", password: "pwd"};
//auth middleware
server.use(function(req,res,next){
if(req.params.username==user.username && req.params.password == user.password){
return next();
}else{
res.send(401);
}
});
server.post('/doc/', function(req,res){
var objToJson = {"result" : "success", "user" : "simon", "location" : "someloc"};
console.log("saved new doc. res: " + util.inspect(objToJson));
res.send(objToJson);
});
//CLIENT
var formdata = require('form-data');
var request = require('request');
var util = require('util');
var fs = require('fs');
var form = new formdata();
form.append('username', 'usr');
form.append('password', 'pwd');
form.append('user', 'someemail#gmail.com');
form.append('file', fs.createReadStream('/some/file.png'));
form.append('filename', "roger123131.png");
form.submit('http://0.0.0.0:7000/doc', function(err, res) {
console.log(res.statusCode);
console.log(res.body);
console.log( "here." + util.inspect(res));
process.exit();
});
In the client, I use form-data module. I need to send over the file, though I'm not sure if this is related/pertinent to the problem at hand.
//CURL REQUEST
curl -v --form username=usr --form password=pwd --form file=#/tmp/0000b.jpg --form user=someemail http://0.0.0.0:7000/doc
The output of the curl request works. My question is, why can i not see the json response when I dump the response object in my node.js client code, but I can when making a request using curl? I'm sure the answer is simple...
EDIT: Here is the output of the node.js client, showing the response object with no evidence of the json object/string:
200
undefined
here.{ _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: [Function: responseOnEnd], readable: [Function] },
_maxListeners: 10,
socket:
{ _connecting: false,
_handle:
{ fd: 10,
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],
free: [Function],
close: [Object],
agentRemove: [Function],
drain: [Function: ondrain],
error: [Function: socketErrorListener] },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
allowHalfOpen: false,
onend: [Function: socketOnEnd],
destroyed: false,
bytesRead: 587,
_bytesDispatched: 23536,
_pendingData: null,
_pendingEncoding: '',
parser:
{ _headers: [],
_url: '',
onHeaders: [Function: parserOnHeaders],
onHeadersComplete: [Function: parserOnHeadersComplete],
onBody: [Function: parserOnBody],
onMessageComplete: [Function: parserOnMessageComplete],
socket: [Circular],
incoming: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] },
_httpMessage:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_headerSent: true,
_header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n',
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
socket: [Circular],
connection: [Circular],
agent: [Object],
socketPath: undefined,
method: 'POST',
path: '/doc',
_headers: [Object],
_headerNames: [Object],
parser: [Object],
res: [Circular] },
ondata: [Function: socketOnData] },
connection:
{ _connecting: false,
_handle:
{ fd: 10,
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],
free: [Function],
close: [Object],
agentRemove: [Function],
drain: [Function: ondrain],
error: [Function: socketErrorListener] },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
allowHalfOpen: false,
onend: [Function: socketOnEnd],
destroyed: false,
bytesRead: 587,
_bytesDispatched: 23536,
_pendingData: null,
_pendingEncoding: '',
parser:
{ _headers: [],
_url: '',
onHeaders: [Function: parserOnHeaders],
onHeadersComplete: [Function: parserOnHeadersComplete],
onBody: [Function: parserOnBody],
onMessageComplete: [Function: parserOnMessageComplete],
socket: [Circular],
incoming: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] },
_httpMessage:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_headerSent: true,
_header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n',
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
socket: [Circular],
connection: [Circular],
agent: [Object],
socketPath: undefined,
method: 'POST',
path: '/doc',
_headers: [Object],
_headerNames: [Object],
parser: [Object],
res: [Circular] },
ondata: [Function: socketOnData] },
httpVersion: '1.1',
complete: false,
headers:
{ 'content-type': 'application/json',
'content-length': '56',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version, Response-Time',
'access-control-allow-methods': 'POST',
'access-control-expose-headers': 'Api-Version, Request-Id, Response-Time',
connection: 'Keep-Alive',
'content-md5': '/HLlB0jKu9S+l17eGyJfxg==',
date: 'Wed, 25 Jun 2014 15:40:00 GMT',
server: 'image-server',
'request-id': 'f7ca8390-fc7e-11e3-aa4e-e9c4573d9f1d',
'response-time': '4' },
trailers: {},
_pendings: [],
_pendingIndex: 0,
url: '',
method: null,
statusCode: 200,
client:
{ _connecting: false,
_handle:
{ fd: 10,
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],
free: [Function],
close: [Object],
agentRemove: [Function],
drain: [Function: ondrain],
error: [Function: socketErrorListener] },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
allowHalfOpen: false,
onend: [Function: socketOnEnd],
destroyed: false,
bytesRead: 587,
_bytesDispatched: 23536,
_pendingData: null,
_pendingEncoding: '',
parser:
{ _headers: [],
_url: '',
onHeaders: [Function: parserOnHeaders],
onHeadersComplete: [Function: parserOnHeadersComplete],
onBody: [Function: parserOnBody],
onMessageComplete: [Function: parserOnMessageComplete],
socket: [Circular],
incoming: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] },
_httpMessage:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_headerSent: true,
_header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n',
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
socket: [Circular],
connection: [Circular],
agent: [Object],
socketPath: undefined,
method: 'POST',
path: '/doc',
_headers: [Object],
_headerNames: [Object],
parser: [Object],
res: [Circular] },
ondata: [Function: socketOnData] },
_consuming: true,
_dumped: false,
httpVersionMajor: 1,
httpVersionMinor: 1,
upgrade: false,
req:
{ domain: null,
_events: { error: [Object], response: [Function] },
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_headerSent: true,
_header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n',
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
socket:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
onend: [Function: socketOnEnd],
destroyed: false,
bytesRead: 587,
_bytesDispatched: 23536,
_pendingData: null,
_pendingEncoding: '',
parser: [Object],
_httpMessage: [Circular],
ondata: [Function: socketOnData] },
connection:
{ _connecting: false,
_handle: [Object],
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: 10,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
onend: [Function: socketOnEnd],
destroyed: false,
bytesRead: 587,
_bytesDispatched: 23536,
_pendingData: null,
_pendingEncoding: '',
parser: [Object],
_httpMessage: [Circular],
ondata: [Function: socketOnData] },
agent:
{ domain: null,
_events: [Object],
_maxListeners: 10,
options: {},
requests: {},
sockets: [Object],
maxSockets: 5,
createConnection: [Function] },
socketPath: undefined,
method: 'POST',
path: '/doc',
_headers:
{ 'content-type': 'multipart/form-data; boundary=--------------------------994987473640480876924123',
host: '0.0.0.0:7000',
'content-length': 23351 },
_headerNames:
{ 'content-type': 'content-type',
host: 'Host',
'content-length': 'Content-Length' },
parser:
{ _headers: [],
_url: '',
onHeaders: [Function: parserOnHeaders],
onHeadersComplete: [Function: parserOnHeadersComplete],
onBody: [Function: parserOnBody],
onMessageComplete: [Function: parserOnMessageComplete],
socket: [Object],
incoming: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] },
res: [Circular] },
pipe: [Function],
addListener: [Function],
on: [Function],
pause: [Function],
resume: [Function],
read: [Function] }
from the docs,
form.submit('http://example.org/', function(err, res) {
// res – response object (http.IncomingMessage) //
res.resume(); // for node-0.10.x
});
Your callback has three parameters, and the response is in the second one.
I found a solution from the the request page (https://github.com/mikeal/request), which requires a small change to the client code:
var r = request.post('http://service.com/upload', function optionalCallback (err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
})
var form = r.form()
form.append('my_field', 'my_value')
form.append('my_buffer', new Buffer([1, 2, 3]))
form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png')))
form.append('remote_file', request('http://google.com/doodle.png'))