Trying to test a HTTP status code in a module but my first response is always undefined
:
foo.js
const pass = require('./bar')
const test = pass('https://www.google.com/') // URL for testing will be API URL
console.log(`The return is: ${test}`)
bar.js
attempt 1:
module.exports = (url) => {
https
.get(url, (res) => {
console.log(res.statusCode)
if (typeof res.statusCode !== 'undefined' && res.statusCode.toString()[0] === '2') {
console.log(`Results: ${res.statusCode}`)
return true
}
function waiting(status) {
if (typeof status !== 'undefined') {
console.log('run timeout')
setTimeout(waiting, 250)
} else {
console.log(`Results: ${status}`)
return true
}
}
})
.on('error', (e) => {
console.error(`Error ${e}`)
return false
})
}
attempt 2:
module.exports = (url) => {
https
.get(url, (res) => {
console.log(res.statusCode)
function waiting(status) {
if (typeof status !== 'undefined') {
console.log('run timeout')
setTimeout(waiting, 250)
} else {
console.log(`Results: ${status}`)
return true
}
}
})
.on('error', (e) => {
console.error(`Error ${e}`)
return false
})
}
other attempts to detect undefined
:
if (typeof res.statusCode === 'number' && res.statusCode !== undefined && res.statusCode !== null) {
if (!res.statusCode) {
if (typeof res.statusCode !== 'undefined') {
console.log(`Results: ${res.statusCode}`)
if (res.statusCode.toString()[0] === '2') return true
return false
}
Research:
- http get NodeJS how to get error status code?
- JavaScript checking for null vs. undefined and difference between == and ===
- http statusCode sometimes undefined
What am I doing wrong? In my module how can I check the status code after the undefined
so I can return a true
or false
from the actual numerical value?