Node.JS请求模块callback不触发

我正在使用node.js的请求模块运行此代码

var hsKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" var hsForm = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" var hsHost = "https://docs.google.com/" var url = hsHost + "forms/d/" + hsForm + "/formResponse" var form = { "entry.129401737": pointsAvg, "entry.2000749128": hiddenNeurons, "submit": "Submit", "formkey": hsKey }; request.post({ url: url, form: form }, function (err, res, body) { console.log("Sent data"); }); 

我试着运行上面的代码只是使用标准的Node.JS库,无济于事。 callback函数永远不会被触发,请求也不会通过。 我不知道为什么。

我相信我已经find了自己的问题的答案。 这个问题似乎是,我没有在Node.js事件循环中分配任何时间来允许执行请求。

看看这个问题 :

你的代码应该看起来像

 var hsKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; var hsForm = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; var hsHost = "https://docs.google.com/" var url = hsHost + "forms/d/" + hsForm + "/formResponse" var form = { "entry.129401737": pointsAvg, "entry.2000749128": hiddenNeurons, "submit": "Submit", "formkey": hsKey }; request.post({ url: url, form: form }, function (response) { response.setEncoding('utf8'); response.on('data', function(chunk){ //do something with chunk }); }); 

data事件在接收到响应时应该被触发。

所以如果你在npm读取请求模块的文档

 request .get('http://google.com/img.png') .on('response', function(response) { console.log(response.statusCode) // 200 console.log(response.headers['content-type']) // 'image/png' }); 

有一个response事件应该被解雇。

我也遇到了这个。 我最终创build了一个单独的js文件,其中只包含请求,没有描述和方法,并用“mocha mynewbarebonesreq.js”运行它。 突然间,我发现有一个例外被摩卡(和标准记者,规范)一起抛出和吞噬。

我终于安装并启用了mocha_reporter,它显示了exception

现在看起来像这样:

 describe('CMSLogin', function () { it('should log in as user ' + JSON.stringify(USER_PASS), function (done) { request({ url: "http://cms.lund.multiq.com:3000/api/CMSUsers/login", method: "POST", headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, json: false, body: JSON.stringify(USER_PASS) }, (err, res, body) => { var parsedBody = JSON.parse(body); this.token = parsedBody.id; console.log(this.token) assert.equal(USER_PASS.userId, parsedBody.userId); assert.doesNotThrow(() => Date.parse(parsedBody.created)); if (err) { done.fail(err); } done(); }); }); }