解析服务器中的 Node.js,空值?

问题描述

我在使用 Parse-server 的 Back4App 中使用 Node.js。我正在尝试从 openweathermap.org 获取天气预报。但我得到一个空的返回值?我不明白为什么? 当在前端使用 Flutter 时,它在相同的 url 下工作完美。

var _weather;

Parse.Cloud.define("WD",(request) => {

var http = require('http');

var options = {
  hostname: 'api.openweathermap.org',path:  '/data/2.5/forecast?q=Malaga&units=metric&appid=mykey'   
 };

callback = function(response) {
  var str = '';

response.on('data',function (chunk) {
    str += chunk;

_weather = JSON.parse(str);
 });  
}
http.request(options,callback).end();
return _weather;

});

解决方法

您不是在等待请求结束并且函数在它发生之前返回。尝试这样的事情(考虑到您使用的是 >3 解析版本):

const http = require('http');

Parse.Cloud.define("WD",async (request) => {
let _weather;

const options = {
  hostname: 'api.openweathermap.org',path:  '/data/2.5/forecast?q=Malaga&units=metric&appid=mykey'   
 };

await new Promise(resolve => {
const callback = function(response) {
  let str = '';

response.on('data',function (chunk) {
    str += chunk;
 });  

response.on('end',function () {
_weather = JSON.parse(str);
resolve();
 });  

}
http.request(options,callback).end();
});

return _weather;

});