Related
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.
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);
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/)
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 :)
I have an array of objects with only ObjectIDs and want to search a collection for all the documents with those IDs.
var array = [{ _id: 5551e59be360594cd3319644 },
{ _id: 5551e59be360594cd3319631 },
{ _id: 5551e59be360594cd33195d2 },
{ _id: 5551e59be360594cd3319627 }];
Here is what I'm currently doing to get my result:
for (var i = 0; i < array.length; i++) {
db.collection('test').findOne({_id:array[i]._id}, function(err, matched) {
console.log(matched);
});
I tried to work with the $inoperator but had no success because it's not an array of IDs but an array of objects with those IDs inside.
Is there another way to do this with just one database query as I don't think it's a great idea to do so many database queries in a for loop.
EDIT
I now tried it with the map method (like #chrisdam explained) so I have an array of the IDs but when i pass it to the find method i get this result:
EDIT2
Nevermind my first edit. find() returns just a cursor, not the documents itself. So I used toArray(). Thanks for your help #chrisdam!!
{ db:
{ domain: null,
_events: {},
_maxListeners: undefined,
databaseName: 'test',
serverConfig: {
domain: null,
_events: {},
_maxListeners: undefined,
auth: [Getter],
_callBackStore: [Object],
_commandsStore: [Object],
_dbStore: [Object],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
_used: true,
replicasetInstance: null,
emitOpen: false,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
serverCapabilities: [Object],
name: 'localhost:27017',
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
socketTimeoutMS: [Getter/Setter],
_readPreference: [Object],
db: [Circular],
dbInstances: [Object],
connectionPool: [Object],
isMasterDoc: [Object] },
options: {
read_preference_tags: null,
read_preference: 'primary',
url: 'mongodb://localhost:27017/test',
native_parser: true,
readPreference: [Object],
safe: false,
w: 1 },
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib: {
BSON: [Object],
Long: [Object],
ObjectID: [Object],
DBRef: [Object],
Code: [Object],
Timestamp: [Object],
Binary: [Object],
Double: [Object],
MaxKey: [Object],
MinKey: [Object],
Symbol: [Object] },
bson: { promoteLongs: true },
bson_deserializer: {
Code: [Object],
Symbol: [Object],
BSON: [Object],
DBRef: [Object],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Object],
MinKey: [Object],
MaxKey: [Object],
promoteLongs: true },
bson_serializer: {
Code: [Object],
Symbol: [Object],
BSON: [Object],
DBRef: [Object],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Object],
MinKey: [Object],
MaxKey: [Object],
promoteLongs: true },
_state: 'connected',
pkFactory: {
[Function: ObjectID]
index: 13651524,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1431517732801,
eventHandlers: {
error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection: {
db: {
domain: null,
_events: {},
_maxListeners: undefined,
databaseName: 'test',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib: [Object],
bson: [Object],
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: [Object],
tag: 1431517732801,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
collectionName: 'sick',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
pkFactory: {
[Function: ObjectID]
index: 13651524,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
serverCapabilities: undefined },
selector: { _id: { '$in': [Object] } },
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
oplogReplay: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
slaveOk: false,
maxTimeMSValue: undefined,
connection: undefined,
transforms: undefined,
totalNumberOfRecords: 0,
items: [],
cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'test.sick' }
You could try the JavaScript's native map method to generate an ObjectIds array that you can then use with the $in operator as follows:
var array = [{ _id: "5551e59be360594cd3319644" },
{ _id: "5551e59be360594cd3319631" },
{ _id: "5551e59be360594cd33195d2" },
{ _id: "5551e59be360594cd3319627" }],
ids = array.map(function (obj){ return ObjectId(obj._id)});
db.collection.find({ "_id": { "$in": ids }});
OR just use the $or operator as:
var array = [{ _id: "5551e59be360594cd3319644" },
{ _id: "5551e59be360594cd3319631" },
{ _id: "5551e59be360594cd33195d2" },
{ _id: "5551e59be360594cd3319627" }],
ids = array.map(function (obj){ return { _id: ObjectId(obj._id) } });
db.collection.find({ "$or": ids });