Show output on browser console using Protractor - angularjs

I want to show messages in the browser's console when executing the tests with Protractor using Jasmine because the browser's console it's more useful and readable and when I use it in protractor with not valid values it always show me a long message like
Object {
closure_uid_824017913: 1230,
flow_:
Object {
events_: Object {},
closure_uid_824017913: 1,
activeFrame_:
Object {
events_: Object {},
closure_uid_824017913: 1033,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
runningFrame_:
Object {
events_: Object {},
closure_uid_824017913: 1033,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
schedulingFrame_:
Object {
events_: Object {},
closure_uid_824017913: 1033,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
shutdownTask_: null,
eventLoopTask_: null,
hold_:
{ _called: false,
_idleTimeout: 2147483647,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 12906,
_onTimeout: [Function: wrapper],
_repeat: [Function] },
yieldCount_: 7 },
stack_: null,
parent_:
Object {
closure_uid_824017913: 1228,
flow_:
Object {
events_: Object {},
closure_uid_824017913: 1,
activeFrame_: [Object],
runningFrame_: [Object],
schedulingFrame_: [Object],
shutdownTask_: null,
eventLoopTask_: null,
hold_: [Object],
yieldCount_: 7 },
stack_: null,
parent_:
Object {
closure_uid_824017913: 1226,
flow_: [Object],
stack_: null,
parent_: [Object],
callbacks_: [Object],
state_: 'pending',
handled_: true,
pendingNotifications_: false,
value_: undefined },
callbacks_: [ [Object] ],
state_: 'pending',
handled_: true,
pendingNotifications_: false,
value_: undefined },
callbacks_: null,
state_: 'pending',
handled_: false,
pendingNotifications_: false,
value_: undefined }
which is everything but useful.

This may help
view console.log output in angular protractor jasmine test
https://ngmilk.rocks/2014/10/17/detecting-console-errors-while-testing-angularjs-with-protractor/)

Related

Node.js accepts request, forms 2xx response, but responds with status code 400

Node.js receives a POST request and responds using:
router.post('/latest', function(req, res, next) {
res.status(202).send(req.body);
console.log(res);
});
Observing the output of console.log(res);, the server seems to formulate a 202... response, but _bytesDispatched is equal to 28, which corresponds to HTTP/1.1 400 Bad Request (the actual response I get on the other side). Why is this so?
Output of console.log(res);:
ServerResponse {
_events: { finish: [Function: bound resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
output:
[ 'HTTP/1.1 202 Accepted\r\nX-Powered-By: Express\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 7\r\nETag: W/"7-7mCT8n6gALm4N/SpGscZkTFIPTE"\r\nDate: Thu, 04 Jul 2019 14:59:08 GMT\r\nConnection: keep-alive\r\n\r\n',
<Buffer 7b 22 62 22 3a 31 7d>,
'' ],
outputEncodings: [ 'latin1', undefined, 'latin1' ],
outputCallbacks: [ null, null, [Function: bound onFinish] ],
outputSize: 223,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 7,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
_consumed: true },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [BufferList],
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,
_events:
{ finish: [Function: onSocketFinish],
end: [Array],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause],
error: [Function] },
_eventsCount: 9,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: true,
ended: true,
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: 1,
prefinished: true,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: false,
_bytesDispatched: 28,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
allowHalfOpen: true,
server:
Server {
_events: [Object],
_eventsCount: 4,
_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::::5761',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 6 },
_server:
Server {
_events: [Object],
_eventsCount: 4,
_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::::5761',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 6 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_unrefed: true,
msecs: 120000,
nextTick: false,
_timer: [Timer] },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_unrefed: true,
msecs: 120000,
nextTick: false,
_timer: [Timer] },
_idleStart: 25909,
_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: [IncomingMessage],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 32,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 33,
[Symbol(triggerAsyncId)]: 32 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
_consumed: true },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [BufferList],
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,
_events:
{ finish: [Function: onSocketFinish],
end: [Array],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause],
error: [Function] },
_eventsCount: 9,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: true,
ended: true,
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: 1,
prefinished: true,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: false,
_bytesDispatched: 28,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
allowHalfOpen: true,
server:
Server {
_events: [Object],
_eventsCount: 4,
_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::::5761',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 6 },
_server:
Server {
_events: [Object],
_eventsCount: 4,
_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::::5761',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 6 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_unrefed: true,
msecs: 120000,
nextTick: false,
_timer: [Timer] },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_unrefed: true,
msecs: 120000,
nextTick: false,
_timer: [Timer] },
_idleStart: 25909,
_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: [IncomingMessage],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 32,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 33,
[Symbol(triggerAsyncId)]: 32 },
_header: 'HTTP/1.1 202 Accepted\r\nX-Powered-By: Express\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 7\r\nETag: W/"7-7mCT8n6gALm4N/SpGscZkTFIPTE"\r\nDate: Thu, 04 Jul 2019 14:59:08 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],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
socket:
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
_bytesDispatched: 28,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
allowHalfOpen: true,
server: [Server],
_server: [Server],
_idleTimeout: 120000,
_idleNext: [TimersList],
_idlePrev: [TimersList],
_idleStart: 25909,
_destroyed: false,
parser: [HTTPParser],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 32,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 33,
[Symbol(triggerAsyncId)]: 32 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
_bytesDispatched: 28,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
allowHalfOpen: true,
server: [Server],
_server: [Server],
_idleTimeout: 120000,
_idleNext: [TimersList],
_idlePrev: [TimersList],
_idleStart: 25909,
_destroyed: false,
parser: [HTTPParser],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 32,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 33,
[Symbol(triggerAsyncId)]: 32 },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ host: '127.0.0.1',
'content-type': 'application/json; charset=utf-8',
'content-length': '7' },
rawHeaders:
[ 'Host',
'127.0.0.1',
'Content-Type',
'application/json; charset=utf-8',
'Content-Length',
'7' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/latest',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 9,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
_bytesDispatched: 28,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
allowHalfOpen: true,
server: [Server],
_server: [Server],
_idleTimeout: 120000,
_idleNext: [TimersList],
_idlePrev: [TimersList],
_idleStart: 25909,
_destroyed: false,
parser: [HTTPParser],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
[Symbol(asyncId)]: 32,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 33,
[Symbol(triggerAsyncId)]: 32 },
_consuming: true,
_dumped: false,
next: [Function: next],
baseUrl: '',
originalUrl: '/latest',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/latest',
path: '/latest',
href: '/latest',
_raw: '/latest' },
params: {},
query: {},
res: [Circular],
body: { b: 1 },
_body: true,
length: undefined,
read: [Function],
route: Route { path: '/latest', stack: [Array], methods: [Object] } },
locals: {},
statusCode: 202,
statusMessage: 'Accepted',
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
{ 'x-powered-by': [ 'X-Powered-By', 'Express' ],
'content-type': [ 'Content-Type', 'application/json; charset=utf-8' ],
'content-length': [ 'Content-Length', '7' ],
etag: [ 'ETag', 'W/"7-7mCT8n6gALm4N/SpGscZkTFIPTE"' ] } }
The actual incoming request (C) looks like this:
POST /latest HTTP/1.1
Host: 127.0.0.1
Content-Type: application/json; charset=utf-8
Content-Length: 7
{"b":1}

Passing parameter to node api

I have been trying to pass multiple parameters from my angular service to node api. Below here is angular service code
getEnrollmentId(userName,org) {
console.log("username",userName);
let headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body1 = new URLSearchParams();
body1.set('username', userName);
body1.set('orgName', org);
let body = body1.toString();
console.log('server logs',body);
return this.http.post('http://localhost:4000/users', body, options )
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error shit '));}
My node api code is
app.post('/users', function(req, res) {
var username = req.body.username;
var orgName = req.body.orgName;
logger.debug('Body request',req);
logger.debug('End point : /users');
logger.debug('User name : ' + username);
logger.debug('Org name : ' + orgName);
if (!username) {
res.json(getErrorMessage('\'username\''));
return;
}
if (!orgName) {
res.json(getErrorMessage('\'orgName\''));
return;
}
var token = jwt.sign({
exp: Math.floor(Date.now() / 1000) + parseInt(config.jwt_expiretime),
username: username,
orgName: orgName
}, app.get('secret'));
helper.getRegisteredUsers(username, orgName, true).then(function(response) {
if (response && typeof response !== 'string') {
response.token = token;
res.json(response);
} else {
res.json({
success: false,
message: response
});
}
});
});
Although I am able to see my parameter's value in body variable , however when on my node console both parameters receiving undefined value.
Below here are node console logs.
As you can see in my request object , body parameter returning empty array body={} which might be the reason parameter value assigned to undefined . Any solution to fix this
[2017-08-07 22:17:06.186] [DEBUG] SampleWebApp - Body 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,
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: 830,
_externalStream: {},
fd: 13,
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: false,
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: 287,
_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: 240000,
_pendingResponseData: 0,
_connectionKey: '6::::4000' },
_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: 240000,
_pendingResponseData: 0,
_connectionKey: '6::::4000' },
_idleTimeout: 240000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 240000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 240000,
nextTick: false },
_idleStart: 46633,
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: 830,
_externalStream: {},
fd: 13,
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: false,
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: 287,
_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: 240000,
_pendingResponseData: 0,
_connectionKey: '6::::4000' },
_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: 240000,
_pendingResponseData: 0,
_connectionKey: '6::::4000' },
_idleTimeout: 240000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 240000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 240000,
nextTick: false },
_idleStart: 46633,
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: 'localhost:4000',
'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0',
accept: 'application/json, text/plain, */*',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate',
'content-type': 'x-www-form-urlencoded',
referer: 'http://localhost:4200/',
'content-length': '26',
origin: 'http://localhost:4200',
connection: 'keep-alive' },
rawHeaders:
[ 'Host',
'localhost:4000',
'User-Agent',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0',
'Accept',
'application/json, text/plain, */*',
'Accept-Language',
'en-US,en;q=0.5',
'Accept-Encoding',
'gzip, deflate',
'Content-Type',
'x-www-form-urlencoded',
'Referer',
'http://localhost:4200/',
'Content-Length',
'26',
'Origin',
'http://localhost:4200',
'Connection',
'keep-alive' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/users',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
bytesRead: 830,
_externalStream: {},
fd: 13,
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: false,
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: 287,
_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: 240000,
_pendingResponseData: 0,
_connectionKey: '6::::4000' },
_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: 240000,
_pendingResponseData: 0,
_connectionKey: '6::::4000' },
_idleTimeout: 240000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 240000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 240000,
nextTick: false },
_idleStart: 46633,
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: '/users',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/users',
path: '/users',
href: '/users',
_raw: '/users' },
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: 287,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 240000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 46633,
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: 287,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 240000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 46633,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] },
_header: null,
_headers:
{ 'x-powered-by': 'Express',
'access-control-allow-origin': '*' },
_headerNames:
{ 'x-powered-by': 'X-Powered-By',
'access-control-allow-origin': 'Access-Control-Allow-Origin' },
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: {} },
body: {},
token: undefined,
route: Route { path: '/users', stack: [ [Object] ], methods: { post: true } } }
[2017-08-07 22:17:06.430] [DEBUG] SampleWebApp - End point : /users
[2017-08-07 22:17:06.430] [DEBUG] SampleWebApp - User name : undefined
[2017-08-07 22:17:06.430] [DEBUG] SampleWebApp - Org name : undefined
You are sending data with 'Content-Type': 'x-www-form-urlencoded' header; if you want to parse the body, I recommended to install body-parse module (see solution proposed here).
Alternatively, if you can change the Content-Type of your request to
'Content-type': 'application/json'
your code on the server side should work as it is.

how to read/save a json file in nodeJs from angularjs $http.post

SORRY FOR BAD ENGLISH
I have a problem trying to catch a json sended using $http.post fron an angularjs to a nodejs with express (i have to send it because i can not save in client side a file on the server)
i have this code in angularjs
var app = angular.module('angularTable', []);
app.controller('listdata',function($scope, $http){
$scope.users = []; //declare an empty array
$http.get("data/people.json").success(function(response){
$scope.users = response; //this works well
});
$scope.add = function(){
$scope.users.push({'id':$scope.users.length,'name':$scope.name,'age': $scope.age}); //this works well
$http.post("data",$scope.users).success(function(data, status, headers, config){ //this send to the nodeJs the object
console.log("success");
}).error(function(data,status,headers,config){
console.log("error");
});
}
});
and this in server nodeJs
var express = require('express');
var app = express();
app.use('/data', express.static(__dirname + '/data/')); //this is for routing
app.post("/data", function(req,res){
console.log(req); //this return me something (that i do not understand)***********
console.log(req.name); //this return me undefined
THIS IS WHERE I NEED THE JSON THAT I SEND FROM ANGULARJS TO SAVE INTO A EXISTENT JSON FILE IN THE SERVER (/data/people.json)
});
app.listen(5050);ยด
this is the json file
[{
"id": 0,
"age": 24,
"name": "Mathis Hurst"
}, {
"id": 1,
"age": 38,
"name": "Gallegos Ryan"
}, {
"id": 2,
"age": 27,
"name": "Jodi Valencia"
}, {
"id": 3,
"age": 28,
"name": "Jenna Anderson"
}, {
"id": 4,
"age": 28,
"name": "Horne Clark"
}, {
"id": 5,
"age": 21,
"name": "Briggs Walters"
}, {
"id": 6,
"age": 27,
"name": "Rena Higgins"
}, {
"id": 7,
"age": 32,
"name": "Adrian Marquez"
}, {
"id": 8,
"age": 25,
"name": "Alberta Ellison"
}, {
"id": 9,
"age": 20,
"name": "Mcleod Stark"
}, {
"id": 10,
"age": 22,
"name": "Neal Patrick"
}, {
"id": 11,
"age": 36,
"name": "Williamson Roman"
}
]
this is what console.log(req); returns:
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
destroyed: false,
bytesRead: 0,
_bytesDispatched: 970,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_connections: 3,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::5050' },
_server:
Server {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_connections: 3,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::5050' },
_idleTimeout: 120000,
_idleNext:
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,
bytesRead: 0,
_bytesDispatched: 244,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Circular],
_idleStart: 2771,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: null },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
_idleStart: 3075,
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,
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: 'localhost:5050',
connection: 'keep-alive',
'content-length': '544',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:5050',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36',
'content-type': 'application/json;charset=UTF-8',
dnt: '1',
referer: 'http://localhost:5050/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'es-419,es;q=0.8,en-US;q=0.6,en;q=0.4',
cookie: '___r56138=0.9179862105555572' },
rawHeaders:
[ 'Host',
'localhost:5050',
'Connection',
'keep-alive',
'Content-Length',
'544',
'Accept',
'application/json, text/plain, */*',
'Origin',
'http://localhost:5050',
'User-Agent',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36',
'Content-Type',
'application/json;charset=UTF-8',
'DNT',
'1',
'Referer',
'http://localhost:5050/',
'Accept-Encoding',
'gzip, deflate',
'Accept-Language',
'es-419,es;q=0.8,en-US;q=0.6,en;q=0.4',
'Cookie',
'___r56138=0.9179862105555572' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/data',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket {
_connecting: false,
_hadError: false,
_handle:
TCP {
_externalStream: {},
fd: 15,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Object],
timeout: [Function],
error: [Function: socketOnError],
close: [Object],
data: [Function: socketOnData],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
destroyed: false,
bytesRead: 0,
_bytesDispatched: 970,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_connections: 3,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::5050' },
_server:
Server {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_connections: 3,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
_pendingResponseData: 0,
_connectionKey: '6::::5050' },
_idleTimeout: 120000,
_idleNext:
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,
bytesRead: 0,
_bytesDispatched: 244,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Circular],
_idleStart: 2771,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: null },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
_idleStart: 3075,
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,
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: '/data',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/data',
path: '/data',
href: '/data',
_raw: '/data' },
params: {},
query: {},
res:
ServerResponse {
domain: null,
_events: { finish: [Function: resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: 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,
bytesRead: 0,
_bytesDispatched: 970,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 3075,
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,
bytesRead: 0,
_bytesDispatched: 970,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 3075,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
read: [Function],
_consuming: true,
_httpMessage: [Circular] },
_header: null,
_headers: { 'x-powered-by': 'Express' },
_headerNames: { 'x-powered-by': 'X-Powered-By' },
_onPendingData: [Function: updateOutgoingData],
req: [Circular],
locals: {} },
route: Route { path: '/data', stack: [ [Object] ], methods: { post: true } } }
If you're looking to generate a json file within Node, first include the fs module:
var fs = require('fs');
Next, add this snippet where you need the json file generated:
fs.writeFile('/data/people.json'), JSON.stringify(req.body, null, 4), function (err) {
if (err) {
console.log('error writing /data/people.json');
} else {
console.log('JSON file written to /data/people.json');
}
});
You're accessing variables wrong.
on POST data, try req.body.yourvariable
on GET data, try req.query.yourvariable
var express = require('express');
var app = express();
app.use('/data', express.static(__dirname + '/data/')); //this is for routing
app.post("/data", function(req,res){
console.log(req.body.name); // this should work.
// your saving routine here.
});
app.listen(5050);

Protractor - How to count elements containing specified text

I'm trying to do something I thought would be very simple but has had me stumped for two days now. I just want to count the number of elements with a specific class that contain a specific line of text.
My code looks like this:
element.all(by.className('interaction-thumb-titlebar')).map(function(element) {
return element.getText();
});
console.log("View names:", viewNames);
From what I've read, this should produce something like the following:
View names: ['apple', 'orange', 'apple', 'banana']
And I'll simply search through this array to count whatever I need to count.
The problem of course is that everything, these days, has been changed to promises rather than actual values, meaning what I actually get is this:
View names: { closure_uid_209027314: 2004,
flow_:
{ events_: {},
closure_uid_209027314: 1,
activeFrame_:
{ events_: {},
closure_uid_209027314: 1954,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
schedulingFrame_:
{ events_: {},
closure_uid_209027314: 1954,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
shutdownTask_: null,
eventLoopTask_: null,
hold_:
{ _idleTimeout: 2147483647,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 1437638541678,
_onTimeout: [Function: wrapper],
_repeat: true },
yieldCount_: 3 },
stack_: null,
parent_:
{ closure_uid_209027314: 2002,
flow_:
{ events_: {},
closure_uid_209027314: 1,
activeFrame_: [Object],
schedulingFrame_: [Object],
shutdownTask_: null,
eventLoopTask_: null,
hold_: [Object],
yieldCount_: 3 },
stack_: null,
parent_:
{ closure_uid_209027314: 2000,
flow_: [Object],
stack_: null,
parent_: [Object],
callbacks_: [Object],
state_: 'pending',
handled_: true,
pendingNotifications_: false,
value_: undefined },
callbacks_: [ [Object] ],
state_: 'pending',
handled_: true,
pendingNotifications_: false,
value_: undefined },
callbacks_: null,
state_: 'pending',
handled_: false,
pendingNotifications_: false,
value_: undefined }
I've even tried changing the line return element.getText(); to return 'turtle' and I get exactly the same output.
Can anyone help me?
Andy
There is a locator by.cssContainingText, which may solve your problem in a bit more elegant way: first parameter it applies is a CSS selector, and the second one is a text you want an element to have. You can then use it in conjunction with a method count:
var els = element.all(by.cssContainingText('.interaction-thumb-titlebar', 'apple'));
expect(els.count()).toBe(2);
So as #gillesc pointed out to me in the question's comments, the issue I am having is that even the map function returns a promise. Promises all the way down! Thankfully, this promise will resolve the promises returned in the map function so the code I needed was like so:
element.all(by.className('interaction-thumb-titlebar')).map(function(element) {
return element.getText();
}).then(function(viewNames){
console.log("View names:" viewNames);
});
console.log("View names:", viewNames);
Now to complete the counting function I needed, the complete solution looks like this:
function countElements (css, text) {
//if no text specified, return number of matching elements with css
if(!text) {
return element.all(by.css(css)).then(function(elements){
return elements.length;
});
}
//if text specified, return number of matching elements with css that have the specifed text
return element.all(by.css(css)).map(function(element) {
return element.getText();
}).then(function(textArray) {
var numElements = 0;
for(var i in textArray) {
if(textArray[i] == text) {
numElements++;
}
}
return numElements;
});
}
Which I can use like so:
expect(countElements('.interaction-thumb-titlebar').toBe(4);
expect(countElements('.interaction-thumb-titlebar', 'apple').toBe(2);

AngularJS & Protractor - getLocationAbsUrl() doesn't return the url (string) but an object

The title is saying it all.
I want to log the url to a console but it gives me some object
spec.js
describe('Protractor Demo App', function() {
it('should add 1 and 2', function() {
browser.get('http://juliemr.github.io/protractor-demo/#/');
element(by.model('first')).sendKeys(1);
element(by.model('second')).sendKeys(2);
element(by.id('gobutton')).click();
console.log(browser.getLocationAbsUrl()); // logs some object
expect(browser.getLocationAbsUrl())
.toEqual('/');
});
});
And this is what I seen in my console
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Started
{ closure_uid_727700741: 274,
flow_:
{ events_: {},
closure_uid_727700741: 1,
activeFrame_:
{ events_: {},
closure_uid_727700741: 75,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
schedulingFrame_:
{ events_: {},
closure_uid_727700741: 75,
flow_: [Circular],
parent_: [Object],
children_: [Object],
lastInsertedChild_: [Object],
pendingTask_: null,
isLocked_: false,
isBlocked_: false,
pendingCallback: false,
pendingRejection: false,
cancellationError_: null },
shutdownTask_: null,
eventLoopTask_: null,
hold_:
{ _idleTimeout: 2147483647,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 95289669,
_onTimeout: [Function: wrapper],
_repeat: true },
yieldCount_: 10 },
stack_: null,
parent_:
{ closure_uid_727700741: 272,
flow_:
{ events_: {},
closure_uid_727700741: 1,
activeFrame_: [Object],
schedulingFrame_: [Object],
shutdownTask_: null,
eventLoopTask_: null,
hold_: [Object],
yieldCount_: 10 },
stack_: { [Task: Protractor.getLocationAbsUrl()] name: 'Task' },
parent_: null,
callbacks_: [ [Object] ],
state_: 'pending',
handled_: true,
pendingNotifications_: false,
value_: undefined },
callbacks_: null,
state_: 'pending',
handled_: false,
pendingNotifications_: false,
value_: undefined }
.
1 spec, 0 failures
Finished in 3.251 seconds
[launcher] 0 instance(s) of WebDriver still running
[launcher] chrome #1 passed
What is that object ?
How can I print the current url to a console ?
As I know browser.getLocationAbsUrl() return the promise and when the promise is resolve it will give you the current url.
Therefore while you are printing it with
console.log(browser.getLocationAbsUrl());
It prints the complete object of promise.
Try out the code below it may help you :-
browser.getCurrentUrl().then(function(actualUrl) {
console.log(actualUrl);
});
you can find the syntax here link
Hope it helps :)

Resources