首页 > 解决方案 > 如何使用nodejs http修复“'listener'参数必须是一个函数”

问题描述

我在纠正我的代码中的这个错误时遇到了麻烦,它在本地环境中运行良好,但在代码进入我的“http.get”调用后立即返回这个错误:““listener”参数必须是一个函数”。Nodejs 版本在两种环境中完全相同,令人不安的是,使用 axios 的 get 可以正常工作,并且具有相同的标头和参数。不幸的是,我不能使用 axios,因为它会截断我要收到的非常重要的十六进制数据以作为此请求的回报。

我尝试以更经典的风格编写函数,但出现了同样的错误。

const http = require('https');
const querystring = require('querystring');
const tokenData = require('../config/token');


const apiDL = {
    baseURL: process.env.DOWNLOAD_API,
    headers : {
        //"Content-Type" : "application/x-www-form-urlencoded",
        "Authorization" :""}

    };

 const singleDownload = (req, res) => {
     //truncating my code to arrive to the problematic part
                        let h = apiDL.headers;
                        h.Authorization = token;
                        let p = params;

                            http.get( apiDL.baseURL,{ path :'/download?' + q, headers : h}, (resp) => {

                                const { statusCode } = resp;
                                const contentType = resp.headers['content-type'];
                                const contentDisp = resp.headers['content-disposition'];

//some other code irrelevant to the problem since the bug occurs when the http.get is called
                            }
                            ).on('error', (e) => {
                                console.error(`Got error: ${e.message}`);
                                er +=e.message;
                              }
                            );

 }





 module.exports = {singleDownload}

我不明白为什么在这种环境中会发生此错误,而在本地却没有相同的参数。我会很感激任何帮助。

标签: javascriptnode.jshttps

解决方案


如果它对未来的任何人有帮助:文档指定这样的调用是可能的:

https.get(url,options,callback);

就我而言,我仍然不知道为什么,它只接受这种调用:

https.get(options,callback);

推荐阅读