0

I have below code:

var port = request.app.settings.port || 3000;

This throws an error:

TypeError: Cannot read property 'settings' of undefined
   at forceLogin (/home/projects/nodejs/node_modules/connect-keycloak/middleware/protect.js:5:25)
   at /home/jaec/WebstormProjects/punters/services-api/node_modules/connect-keycloak/middleware/protect.js:44:5
   at call (/home/jaec/WebstormProjects/punters/services-api/node_modules/connect/lib/proto.js:210:7)
   at next (/home/jaec/WebstormProjects/punters/services-api/node_modules/connect/lib/proto.js:154:5)
   at Function.app.handle (/home/jaec/WebstormProjects/punters/services-api/node_modules/connect/lib/proto.js:157:3)
   at Server.app (/home/jaec/WebstormProjects/punters/services-api/node_modules/connect/lib/connect.js:28:37)
   at Server.emit (events.js:98:17)
   at HTTPParser.parser.onIncoming (http.js:2113:12)
   at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:122:23)
   at Socket.socket.ondata (http.js:1971:22)

Is there a reason why it's not picking up default which is 3000?

Passionate Engineer
  • 10,034
  • 26
  • 96
  • 168
  • By default `request` has no attribute named `app`.... So unless you added it... I think you made some mistake. – sarveshseri Feb 04 '15 at 00:16
  • 1
    And if you wanted to check for first option and supply other in case it was not present you should have done this - `var port = ( request.app && request.app.settings && request.app.settings.port ) || 3000;` It will first check for presence of `request.app.settings.port` but assign 3000 if it were not present. – sarveshseri Feb 04 '15 at 00:20

2 Answers2

0
//This would have worked:
var port = undefined || 3000;

//this throws an error
var port = undefined.settings || 3000

undefined does not have properties

var object = { };
object.prop // undefined
object.prop.another // throws an error
user1695032
  • 1,112
  • 6
  • 10
0

I think what you want is to check if request.app.settings.port is defined and assign its value but assign 3000 if it is not defined.

In that case you want to do following,

var port = ( request.app && request.app.settings && request.app.settings.port ) || 3000;
sarveshseri
  • 13,738
  • 28
  • 47