Related
Okay, so I have what is effectively two identical (to my eyes at least!) pieces of Node JS code. The only difference is that in once case it is wrapped up in a function and called via that function and in the other case, the code sits outside any function. When I run the two pieces, of what should be identical code, I get vastly different results. Why is this?
Here is the code when not inside of a function:
chunks = []
req = https.get('https://www.example.com',
res => {
res.setEncoding('utf8')
res.on('data', chunk => {
chunks.push(chunk)
})
res.on('end', function(){
chunks.join()
})
}).end()
console.log(chunks[0])
Here is me using what, as far as I can tell, should effectively be the exact same code but via a function format:
function readURI(uri){
const chunks = []
const req = https.get(uri, res => {
res.setEncoding('utf8')
res.on('data', chunk => {
chunks.push(chunk)
})
res.on('end', function(){
chunks.join()
})
})
req.end()
return chunks[0]
}
console.log(readURI('https://www.example.com'))
I run both of these in the Node REPL. In the first instance, chunks[0] is a string with the content of the website as I expect. In the second, I get no data in the return of the function. Why would this happen?
There are two things at play here.
When a line is evaluated, the completion value of the line is displayed when using the Node REPL - even if the line doesn't include a console.log. As a result, the first code's req = https.get('https://www.example.com', logs the request object.
Look at what gets logged carefully - it really does not contain the content of the website anywhere - the request is asynchronous, it has not finished by the time the final line is executed.
Welcome to Node.js v14.17.6.
Type ".help" for more information.
> const https = require('https');
undefined
> chunks = []
[]
> req = https.get('https://www.example.com',
... res => {
..... res.setEncoding('utf8')
..... res.on('data', chunk => {
....... chunks.push(chunk)
....... })
..... res.on('end', function(){
....... chunks.join()
....... })
..... }).end()
ClientRequest {
_events: [Object: null prototype] {
response: [Function: bound onceWrapper] { listener: [Function (anonymous)] }
},
_eventsCount: 1,
_maxListeners: undefined,
outputData: [
{
data: 'GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n',
encoding: 'latin1',
callback: [Function: bound onFinish]
}
],
outputSize: 60,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: null,
_header: 'GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype] {
free: [Function (anonymous)],
newListener: [Function: maybeEnableKeylog]
},
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
>
options: { path: null },
requests: {},
sockets: { 'www.example.com:443:::::::::::::::::::::': [Array] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
maxCachedSessions: 100,
_sessionCache: { map: {}, list: [] },
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'www.example.com',
protocol: 'https:',
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] { host: [ 'Host', 'www.example.com' ] }
}
> console.log(chunks[0])
undefined
undefined
>
The website content is not in there - in either version of your code, as expected. It's just that your first code has the request as a completion value of a line, but the second code does not - and in the function version, chunks is an empty array when readURI finishes, so undefined is returned.
Unless you're sure you know exactly how the REPL works, to avoid confusing yourself, I'd recommend running scripts as their own files - eg node example.js - for anything that isn't exceedingly trivial.
This was a simple mistake in interacting with the REPL. In entering the code into the REPL, I did so without a new line on the last line of code and so the request object has been made and completed by the time I hit enter on the final console.log line. In the case of the function based snippet, this doesn't matter as the request is made in the same line and doesn't have time to complete by the time the log is made.
I have the following code listing the files in the folder. Then trying to send them to the post/upload in the express backend. But the files is always undefined. However it seems like size and other info get through.
Client send
const axios = require('axios');
var FormData = require('form-data');
//requiring path and fs modules
const path = require('path');
const fs = require('fs');
//joining path of directory
const directoryPath = path.join(__dirname, '');
//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
var postInfo = files.forEach(async function (file) {
const form_data = new FormData();
form_data.append('file', fs.createReadStream(file));
const request_config = {
method: "post",
url: 'http://localhost:8080/upload',
port: 8080,
headers: {
"Content-Type": "multipart/form-data; boundary=form_data._boundary"
},
data: form_data
};
try {
var req = await axios(request_config);
// Do whatever you want to do with the file
console.log("Request: ", req);
} catch (e) {
console.error(e);
}
});
console.log(postInfo);
});
receiving code in the backend
const http = require('http')
const port = 8080
const express = require('express');
const app = express();
const multer = require('multer');
const server = http.createServer(app)
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({ storage }).single('file');
app.post('/upload', upload, (req, res) => {
console.log(req.files) // this does log the uploaded image data.
})
// bind the server on port
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
Log:
node file-receive.js
server is listening on 8080
undefined
undefined
undefined
response: undefined,
isAxiosError: true,
toJSON: [Function] }
{ Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:194:15)
at endReadableNT (_stream_readable.js:1103:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
code: 'ECONNRESET',
config:
{ url: 'http://localhost:8080/upload',
method: 'post',
data:
FormData {
_overheadLength: 169,
_valueLength: 0,
_valuesToMeasure: [Array],
writable: false,
readable: true,
dataSize: 0,
maxDataSize: 2097152,
pauseStreams: true,
_released: true,
_streams: [],
_currentStream: null,
_insideLoop: false,
_pendingNext: false,
_boundary: '--------------------------046964089061111513973474',
_events: [Object],
_eventsCount: 1 },
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'axios/0.19.2' },
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
port: 8080 },
request:
Writable {
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
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,
emitClose: true,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
_events:
[Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError] },
_eventsCount: 2,
_maxListeners: undefined,
_options:
{ protocol: 'http:',
maxRedirects: 21,
maxBodyLength: 10485760,
path: '/upload',
method: 'POST',
headers: [Object],
agent: undefined,
agents: [Object],
auth: undefined,
hostname: 'localhost',
port: '8080',
nativeProtocols: [Object],
pathname: '/upload' },
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 983,
_requestBodyBuffers: [ [Object], [Object], [Object] ],
_onNativeResponse: [Function],
_currentRequest:
ClientRequest {
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: true,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header:
'POST /upload HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: axios/0.19.2\r\nHost: localhost:8080\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/upload',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
_currentUrl: 'http://localhost:8080/upload' },
response: undefined,
isAxiosError: true,
toJSON: [Function] }
I was able to reproduce the issue and was able to fix the code with the following ajdustments (note that I'm uploading a single file for sake of simplicty).
On the client side you basically just provide the form-data to axios and call getHeaders() to get the already set up header - also you need to adjust the file-name in the form.
// client.js
...
const form_data = new FormData();
form_data.append('file', fs.createReadStream(__dirname + '/file-you-want-to-upload'));
const request_config = {
method: "post",
url: 'http://localhost:8080/upload',
port: 8080,
data: form_data,
headers: form_data.getHeaders()
};
...
On the backend side you need to make sure to access file not files as you're using upload.single and actually send a response in your handler as the resposse would hang otherwise:
//server.js
...
const upload = multer({storage}).single('file');
app.post('/upload', upload, (req, res) => {
console.log(req.file) // this does log the uploaded image data.
res.send("File uploaded");
});
...
When I authorize, it passes without errors, but I can’t get a token for further requests (get, post).
As a result, I should get such a token:
{
"token": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJyb2xlX25hbWUiOiLQkNC00LzQuNC90LjRgdGC0YDQsNGC0L7RgCIsImlhdCI6MTU4NTI5MDY5MSwiZXhwIjoxNTg1Mjk0MjkxfQ.saODDtA27NAf6hThUhvltfv6bpeieWDQ8bYxLhjq6Dc"
}
But I do not see him in the object.
Result:
Request {
maxAttempts: 4,
retryDelay: 5000,
fullResponse: true,
attempts: 1,
options: {
url: 'http://localhost:3000/api/auth/login',
method: 'POST',
json: { username: 'admin', password: '123456' },
maxAttempts: 5,
retryDelay: 5000,
fullResponse: true,
promiseFactory: [Function: defaultPromiseFactory]
},
retryStrategy: [Function: HTTPError],
delayStrategy: [Function],
_timeout: null,
_req: Request {
_events: [Object: null prototype] {
error: [Function: bound ],
complete: [Function: bound ],
pipe: [Function]
},
_eventsCount: 3,
_maxListeners: undefined,
method: 'POST',
maxAttempts: 5,
retryDelay: 5000,
fullResponse: true,
promiseFactory: [Function: defaultPromiseFactory],
callback: [Function],
readable: true,
writable: true,
explicitMethod: true,
_qs: Querystring {
request: [Circular],
lib: [Object],
useQuerystring: undefined,
parseOptions: {},
stringifyOptions: {}
},
_auth: Auth {
request: [Circular],
hasAuth: false,
sentAuth: false,
bearerToken: null,
user: null,
pass: null
},
_oauth: OAuth { request: [Circular], params: null },
_multipart: Multipart {
request: [Circular],
boundary: 'd1a5b314-42ec-44c0-87ab-c4ebf0a28613',
chunked: false,
body: null
},
_redirect: Redirect {
request: [Circular],
followRedirect: true,
followRedirects: true,
followAllRedirects: false,
followOriginalHttpMethod: false,
allowRedirect: [Function],
maxRedirects: 10,
redirects: [],
redirectsFollowed: 0,
removeRefererHeader: false
},
_tunnel: Tunnel {
request: [Circular],
proxyHeaderWhiteList: [Array],
proxyHeaderExclusiveList: []
},
headers: {
host: 'localhost:3000',
accept: 'application/json',
'content-type': 'application/json',
'content-length': 40
},
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: {},
dests: [],
__isRequestRequest: true,
_callback: [Function: bound ] AsyncFunction,
uri: Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:3000',
port: '3000',
hostname: 'localhost',
hash: null,
search: null,
query: null,
pathname: '/api/auth/login',
path: '/api/auth/login',
href: 'http://localhost:3000/api/auth/login'
},
proxy: null,
tunnel: false,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: '3000',
host: 'localhost',
path: '/api/auth/login',
_json: true,
body: '{"username":"admin","password":"123456"}',
httpModule: {
_connectionListener: [Function: connectionListener],
METHODS: [Array],
STATUS_CODES: [Object],
Agent: [Function],
ClientRequest: [Function: ClientRequest],
IncomingMessage: [Function: IncomingMessage],
OutgoingMessage: [Function: OutgoingMessage],
Server: [Function: Server],
ServerResponse: [Function: ServerResponse],
createServer: [Function: createServer],
get: [Function: get],
request: [Function: request],
maxHeaderSize: [Getter],
globalAgent: [Getter/Setter]
},
agentClass: [Function: Agent] { defaultMaxSockets: Infinity },
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: {},
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256
}
},
_callback: null,
_resolve: [Function: promiseResolve],
_reject: [Function: promiseReject],
_promise: Promise {
_handler: Pending {
consumers: undefined,
receiver: undefined,
handler: undefined,
resolved: false
}
},
reply: [Function: requestRetryReply]
}
request:
const auth = {
username : "admin",
password : "123456"
}
var options = {
url: `${config.url}/api/auth/login`,
method: 'POST',
json: auth
};
try {
var result = request(options);
console.log(result)
} catch {
console.log('[ERROR]:', err);
}
Didn't you forget the callback? I mean:
const auth = {
username : "admin",
password : "123456"
}
var options = {
url: `${config.url}/api/auth/login`,
method: 'POST',
json: auth
};
request(options, function(err, res, body) {
if(err){
console.log('[ERROR]:', err);
}
else{
let result = JSON.parse(body);
console.log(result);
}
});
...
I am struggling to successfully execute create calls on the mautic REST api. In my node project I am using a standard express installation and a wrapper for the node api https://github.com/sambarnes90/node-mautic
I have authenticated my machine with the api and can PULL data without problem. The problem is POSTing data to it.
The documentation for the targeted post request is here: https://developer.mautic.org/#create-dynamic-content
This is my route. It derives from the example in node-mautic which works fine, but putting something into mautic does not work for me:
router.get('/api', function(req, res, next) {
//check auth and create config object
mautic.auth.checkAuth(function(config) {
// if all worked
if (config.auth_object) {
var testbody = {
"name": "apitest2"
}
//create call
mautic.dynamiccontent.createDynamicContent(config, testbody, function(data) {
console.log(data);
return res.send(data);
});
//request call for id=3
/*mautic.dynamiccontent.getDynamicContent(config, 3, function(data) {
console.log(data);
return res.send(data);
});
});*/
}
});
});
I am getting this response from the API:
[ { code: 400,
message: 'name: A name is required.',
details: { name: [Array] } } ]
This is the GitHub project for this: https://github.com/raphaelurban/mautic-api-test
EDIT:
I also tried:
var testbody = new Array();
testbody['name'] = 'apitest2';
with the same result.
Here is the full POST request:
Request {
domain: null,
_events:
{ error: [Function: bound ],
complete: [Function: bound ],
pipe: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
body: '{"name":"apitest2"}',
callback: [Function],
method: 'POST',
readable: true,
writable: true,
explicitMethod: true,
_qs:
Querystring {
request: [Circular],
lib: { formats: [Object], parse: [Function], stringify: [Function] },
useQuerystring: undefined,
parseOptions: {},
stringifyOptions: {} },
_auth:
Auth {
request: [Circular],
hasAuth: false,
sentAuth: false,
bearerToken: null,
user: null,
pass: null },
_oauth: OAuth { request: [Circular], params: null },
_multipart:
Multipart {
request: [Circular],
boundary: 'afa47f83-3327-4d67-982d-4db6daab8a39',
chunked: false,
body: null },
_redirect:
Redirect {
request: [Circular],
followRedirect: true,
followRedirects: true,
followAllRedirects: false,
followOriginalHttpMethod: false,
allowRedirect: [Function],
maxRedirects: 10,
redirects: [],
redirectsFollowed: 0,
removeRefererHeader: false },
_tunnel:
Tunnel {
request: [Circular],
proxyHeaderWhiteList:
[ 'accept',
'accept-charset',
'accept-encoding',
'accept-language',
'accept-ranges',
'cache-control',
'content-encoding',
'content-language',
'content-location',
'content-md5',
'content-range',
'content-type',
'connection',
'date',
'expect',
'max-forwards',
'pragma',
'referer',
'te',
'user-agent',
'via' ],
proxyHeaderExclusiveList: [] },
headers: { host: 'hrutest.mautic.net', 'content-length': 19 },
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: {},
dests: [],
__isRequestRequest: true,
_callback: [Function],
uri:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'hrutest.mautic.net',
port: 443,
hostname: 'hrutest.mautic.net',
hash: null,
search: '?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
query: 'access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
pathname: '/api/dynamiccontents/new',
path: '/api/dynamiccontents/new?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
href: 'https://hrutest.mautic.net/api/dynamiccontents/new?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA' },
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'hrutest.mautic.net',
path: '/api/dynamiccontents/new?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
httpModule:
{ Server: { [Function: Server] super_: [Object] },
createServer: [Function: createServer],
globalAgent:
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] },
Agent: { [Function: Agent] super_: [Object] },
request: [Function: request],
get: [Function: get] },
agentClass:
{ [Function: Agent]
super_: { [Function: Agent] super_: [Object], defaultMaxSockets: Infinity } },
agent:
Agent {
domain: null,
_events: { free: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: { path: null },
requests: {},
sockets: { 'hrutest.mautic.net:443:::::::::': [Array] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: { map: [Object], list: [Array] } } }
I haven't had much chance to test any more of this wrapper in recent months.
I would try sending it as an array though if possible?
Try these two combinations of testbody:
var testbody = [
"name": "apitest2"
]
Or
var testbody = {[
"name": "apitest2"
]}
And see what results you get?
Can you possibly get full logs of the request?
Finally I worked it out. At least it is some solution, I am not sure if this also works with the current function.
I found that all other tutorials use form instead of body when posting data. Additionally, their objects do not get JSON.stringified.
So with my object:
var testbody = {
name: 'apitest99'
};
It works when I change the function in node-mautic:
createDynamicContent: function(config, queryParameters, callback) {
var url = config.api_endpoint + "/dynamiccontents/new?access_token=" + config.auth_object.access_token;
//queryParameters = JSON.stringify(queryParameters);**
request.post({
url: url,
form: queryParameters
}, function(err, res) {
if (err) {
callback(err);
} else {
var asset = JSON.parse(res.body);
callback(asset);
}
})
},
And I am getting the following response from the API:
{ dynamicContent:
{ isPublished: true,
dateAdded: '2018-07-13T09:37:07+00:00',
dateModified: null,
createdBy: 1,
createdByUser: 'Raphael',
modifiedBy: null,
modifiedByUser: null,
id: 10,
name: 'apitest99',
category: null,
publishUp: null,
publishDown: null,
sentCount: 0,
variantParent: null,
variantChildren: [],
content: null,
filters: [],
isCampaignBased: true,
slotName: '' } }
I'm new to skill dev and am trying to make an API call from within an intent (for the sake of this example, I am just using Google). For whatever reason, the log statements never execute in my HTTP request:
var test = http.get('http://www.google.com', function (result) {
console.log('Success, with: ' + result.statusCode);
}).on('error', function (err) {
console.log('Error, with: ' + err.message);
});
console.log('test is', test);
The test log statement after the request returns a ClientRequest object. Below is the full log output:
START RequestId: aaa9d350-3c3c-11e7-8840-4bab41953f86 Version: $LATEST
2017-05-19T02:41:32.961Z aaa9d350-3c3c-11e7-8840-4bab41953f86 Warning: Application ID is not set
2017-05-19T02:41:33.139Z aaa9d350-3c3c-11e7-8840-4bab41953f86 test is ClientRequest {
domain: null,
_events:
{ response: { [Function: g] listener: [Function] },
socket: { [Function: g] listener: [Function: onSocket] },
error: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
output: [ 'GET / HTTP/1.1\r
Host: www.google.com\r
Connection: close\r
\r
' ],
outputEncodings: [ 'latin1' ],
outputCallbacks: [ [Function: finish] ],
outputSize: 59,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedHeader: {},
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: null,
connection: null,
_header: 'GET / HTTP/1.1\r
Host: www.google.com\r
Connection: close\r
\r
',
_headers: { host: 'www.google.com' },
_headerNames: { host: 'Host' },
_onPendingData: null,
agent:
Agent {
domain: null,
_events: { free: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: { path: null },
requests: {},
sockets: { 'www.google.com:80:': [Object] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256 },
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/',
_ended: false }
END RequestId: aaa9d350-3c3c-11e7-8840-4bab41953f86
REPORT RequestId: aaa9d350-3c3c-11e7-8840-4bab41953f86 Duration: 338.91 ms Billed Duration: 400 ms Memory Size: 128 MB Max Memory Used: 46 MB
I thought it must be related to it being an async function, but I haven't had any luck.
Is it possibly a setting in AWS Lambda that I need to configure?