首页 > 解决方案 > 进程崩溃:TypeError:回调不是函数

问题描述

我正在尝试调用具有 HTTP 发布请求的此函数,以便我可以在更大脚本的不同部分获取正文

下面是代码:

var request = require('request')
var myJSON = require("JSON");

function getJSON ( input, callback){
var all = {
  'documents': [
    {
      'id': '1',
      // Change this text to test
      'text': 'not helpful' 
    }
  ]
};
request({
    headers: {
      'Content-Type': 'application/json',
      'Ocp-Apim-Subscription-Key' :'0df563b09d8b42b095dd32158e4afd13',
      'Host' : 'westus.api.cognitive.microsoft.com'
    },
    uri: 'https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment',
      json: true,

    body: all,
    method: 'POST'
  }, function (error, response, body) {

         if (error || response.statusCode !== 200) {
       callback(error || {statusCode: response.statusCode});
    }
    else
    callback(body);  
    return callback;
  });
}

 body = getJSON("test");

标签: node.jshttppostcallbackrequest

解决方案


在您的代码片段中,当您调用函数 getJSON 时,您没有提供回调参数。

body = getJSON("test"); // <--- Missing parameter

意思是,getJSON("test") 缺少回调参数。IE getJSON("test", function(){console.log("Do something")});

这可能会导致回调参数未定义。


推荐阅读