首页 > 解决方案 > 使用 https 我如何对未定义的状态代码进行条件化?

问题描述

尝试在模块中测试 HTTP 状态代码,但我的第一个响应始终是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

尝试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
    })
}

尝试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
    })
}

其他检测尝试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
}

研究:

我究竟做错了什么?在我的模块中,如何检查之后的状态代码,undefined以便我可以返回 atruefalse从实际数值返回?

标签: node.jshttpsundefined

解决方案


在您的两次尝试中,您在 bar.js 中导出的函数都没有返回任何内容。由于您正在调用异步函数 ( https.get),因此您也需要导出的函数是异步的。您可以转换您的函数使用承诺并在调用方使用 async/await。例如

foo.js

const pass = require('./bar');

(async function() {
    const test = await pass('https://www.google.com/'); // URL for testing will be API URL

    console.log(`The return is: ${test}`);
})();

请注意 IFEE 以获取异步范围,按照:using await on global scope without async 关键字

bar.js

const https = require('https');

module.exports = (url) => {
    return new Promise((resolve, reject) => {
        https
        .get(url, (res) => {
            console.log(res.statusCode)
            if (typeof res.statusCode !== 'undefined' && res.statusCode.toString()[0] === '2') {
                console.log(`Results: ${res.statusCode}`)
                resolve(true)
            } else {
                resolve(false)
            }
        })
        .on('error', (e) => {
            console.error(`Error ${e}`)
            resolve(false)
        })
    });
}

或者,您可以使用如下回调:

foo.js

const pass = require('./bar');

pass('https://www.google.com/', test => {
    console.log(`The return is: ${test}`);
}); 

bar.js

const https = require('https');

module.exports = (url, callback) => {
    https
    .get(url, (res) => {
        console.log(res.statusCode)
        if (typeof res.statusCode !== 'undefined' && res.statusCode.toString()[0] === '2') {
            console.log(`Results: ${res.statusCode}`)
            callback(true)
        } else {
            callback(false)
        }
    })
    .on('error', (e) => {
        console.error(`Error ${e}`)
        callback(false)
    })
}

推荐阅读