TypeError: callback is not a function in Node.js

TypeError: callback is not a function in Node.js

我正在学习 node.js 下面是我的代码

app.js :

const forecastService  = require('./forecast')

forecastService('New York', (error,data) => {

    if(error){
        console.log('Error in getWeatherForecast ')
    }else {
        console.log('data '+data)
    }
})

forecast.js :

const request  = require('request')

const getWeatherForecast = (city,callback) => {

    console.log('printing typeof callback ..'+typeof callback) 
    // prints function 
    console.log('printing callback ..'+callback)
    //prints actual function definition 

    const api = 'http://api.weatherstack.com/current?access_key=abcdefghijklmn'

    const weather_url = api + '&request='+city
    request({url:weather_url, json:true} , (error,response,callback) => {

        if(error){       
            callback('unable to connect to weather service',undefined)
        }else (response.body.error){
            const errMessage = 'Error in Response :'+response.body.error.info 
            console.log(errMessage)
            callback(errMessage,undefined) // getting error here 
        }
    }) 
}

module.exports = getWeatherForecast

问题:

forecast.js 中,在 callback(errMessage,undefined) 行,我收到错误 - TypeError: callback is not a function

我还在 forecast.js 中打印了 callback as typeof callback = function and callback = actul function definition

但我仍然不知道错误是什么。

有人可以帮忙吗?

我浏览了 public 个像 TypeError : callback is not a function 这样的帖子,其中所有人都说回调没有作为参数正确传递,但我似乎不是这样

问题是你的request-callback定义有误。根据 docs

The callback argument gets 3 arguments:

  • An error when applicable (usually from http.ClientRequest object)
  • An http.IncomingMessage object (Response object)
  • The third is the response body (String or Buffer, or JSON object if the json option is supplied)

很明显,第三个参数不是函数,实际上你是 shadowing 来自外部作用域的回调。您可以通过简单地删除第三个参数来解决此问题:

request({url:weather_url, json:true} , (error,response) => {

        if(error){       
            callback('unable to connect to weather service',undefined)
        }else if (response.body.error){
            const errMessage = 'Error in Response :'+response.body.error.info 
            console.log(errMessage)
            callback(errMessage,undefined) // getting error here 
        } else {
           // handle success
           callback(undefined, response.body);
        }
}) 

忠告 - 您应该使用 Promises and async/await 而不是回调,因为它大大提高了代码的可读性和流程。