默认条件在Node中不起作用

时间:2015-02-04 00:08:12

标签: javascript node.js restify

我的代码如下:

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

这会引发错误:

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)

有没有理由不接受默认值3000?

2 个答案:

答案 0 :(得分:0)

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

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

undefined没有属性

var object = { };
object.prop // undefined
object.prop.another // throws an error

答案 1 :(得分:0)

我认为你想要的是检查是否定义了request.app.settings.port并分配了它的值,但是如果没有定义则分配3000

在这种情况下,您想要关注,

var port = ( request.app && request.app.settings && request.app.settings.port ) || 3000;