John Smith
John Smith

Reputation: 1876

coffeescript/node: undefined var but unsure why

I have those lines of code in coffeescript:

  useragent = if req and req.headers then req.headers['user-agent'] else ""
  isIE = ~useragent.toLowerCase().indexOf('msie')

however this code started throwing errors out of nowhere after running for several months:

TypeError: Cannot call method 'toLowerCase' of undefined

any clue about what might be wrong?

Upvotes: 0

Views: 42

Answers (1)

elclanrs
elclanrs

Reputation: 94101

req.headers['user-agent'] could be undefined as well. Try the following:

useragent = req?.headers?['user-agent'] ? ''
isIE = 'msie' in useragent.toLowerCase()

It assumes user-agent if found will always be a string. Otherwise you'd want to check for the type explicitly.

Upvotes: 1

Related Questions