繁体   English   中英

NodeJS http.request在数据处理之前结束处理

[英]NodeJS http.request end processing before data processes

有人可以解释为什么在实际检索任何数据之前运行http.request结束函数吗? 我将如何进一步调试呢? 我应该检查http状态吗?

这将与Google Home应用一起使用,但是我取出了该代码,并在本地运行时遇到了同样的错误。 http.request来自老师在课堂上提供的内容。

您可以将people /?search = Luke%20Skywalker粘贴到http://swapi.com (SW = StarWars API)中以查看预期结果。

 'use strict'; /*eslint no-undef: "error"*/ /*eslint-env node*/ /*eslint-disable no-console */ let http = require('http'); let starWarsAPI = `www.swapi.co`; //function to get details of the Star Wars Characters //exports.handler = function(event, context, callback) { //console.log("event=" + JSON.stringify(event)); //console.log("context=" + JSON.stringify(context)); //let characterName = event.result.parameters.StarWarsCharacter; let characterName = "Luke Skywalker"; console.log("**** characterName=" + characterName); let options = searchPeopleRequestOptions(characterName); console.log("options=" + JSON.stringify(options)); makeRequest(options, function( data, error) { console.log(" Processing data.results"); let person = data.results[0]; if (person) { let height = person.height; let mass = person.mass; let response = person.name + " is " + height + " centimeters tall, weighs " + mass + " kilograms"; console.log("**** response=" + response); //callback(null, {"speech": response}); } else { console.log ("No person found"); //callback(null, {"speech": "I'm not sure that character exists!"}); } }); //}; console.log("The end"); //create a function to read first and last names from the API. function searchPeopleRequestOptions(argCharacterName) { var pathValue = `/api/people/?search=`+ encodeURIComponent(argCharacterName); return { host: starWarsAPI, path: pathValue }; } function makeRequest(options, callback) { var responseString = ""; var request = http.request(options, function(response) { response.on('data', function(data) { responseString += data; console.log("responseString=" + responseString); }); response.on('end', function() { console.log("end: responseString=" + responseString); // dies on next line because responseString is empty var responseJSON = JSON.parse(responseString); callback(responseJSON, null); }); response.on('error', function (error) { console.log('\\n Error received: ' + error); }); }); request.end(); } 

这是我运行它时看到的:

E:\GitHub\NealWalters\GoogleHomeTest
λ node indexTest.js
**** characterName=Luke Skywalker
options={"host":"www.swapi.co","path":"/api/people/?search=Luke%20Skywalker"}
The end
end: responseString=
undefined:1

我不确定是什么写出了“ undefined:1”这一行。

如果查看服务器的响应状态代码,它将为301: Moved Permanently

而响应的位置字段的值为:

https://swapi.co/api/people/?search=Luke%20Skywalker

代替

http://swapi.co/api/people/?search=Luke%20Skywalker

如我们所见,协议从http更改为https

问题在于,node.js随附的http客户端不支持永久更改URL的重定向。

因此,您可以使用https模块代替http (只需更改require('https') )。

或使用支持重定向的软件包。 例如axiosrequest

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM