API Request 正确返回,但在回调函数中为空

米巴克3

我正在使用 npm Express 和 Request 模块通过 API 获取电影信息:

var express = require("express");
var app = express();
var request = require("request");

app.get("/results", function(req, res){
    console.log(getBody("http://www.omdbapi.com/?s=The+Shining&page=1&apikey=myKey"));
});

function getBody(requestString){
    request(requestString, function(error, response, body){
        return body;
    };
}

为了可读性,我在这里删除了对请求的错误检查。

在请求中,记录“body”表明请求确实返回了正确的 JSON。但是,当我返回 app.get 时,日志记录的值是未定义的。

是不是不能把这个值返回给 app.get 的回调函数?

安迪

request 是一个异步函数,因此您需要使用多种技术(回调、承诺等)中的一种来成功返回数据。

这是一个带有回调的示例:

app.get("/results", function(req, res) {
  getBody(endpoint, function (data) {
    console.log(data);
  });
});

function getBody(endpoint, callback) {
  request(endpoint, function(error, response, body) {
    callback(body);
  });
}

以及使用承诺的示例:

app.get("/results", function(req, res) {
  getBody(endpoint).then(function (data) {
    console.log(data);
  });
});

function getBody(endpoint, callback) {
  return new Promise(function (resolve, reject) {
    request(endpoint, function(error, response, body) {
      if (error) reject('Request failed');
      resolve(body);
    });  
  });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Google Places附近的API成功200,但在Laravel中返回“ INVALID_REQUEST”

使用Request的request函数时,Github API响应为403

Angular中的Twitter API Request_Token

如何理解scrapy.Request中的回调函数?

关于request.addListener的回调函数

如何在api request函数内部调用函数?

正确的 Facebook Graph Api Video Insitghts Request PHP SDK

Google附近的地方Api正在返回INVALID_REQUEST

使用Google API刷新令牌并返回invalid_request

Google Places API返回INVALID_REQUEST(Android)

PHP:为 RESTful API 执行 cURL --location --request

Api request 在 swagger 和 postman 中有效,但在 js 中无效(使用 axios)

Java调用API:从Java代码中回调C函数

DataTables - this.api 用于回调函数中的多个表

使用PostgreSQL和json-api的Post Request返回一个空的正文

Ajax get Request为Azure Ad Graph API返回“未经授权”

DRF-request.user在从提取中调用api期间登录时在APIView中返回AnonymousUser

如何使用Google Places API中的函数添加Google API密钥和回调函数

使用Python中的request包使用API密钥调用REST API

YouTube API TypeError:回调不是函数

Web动画API回调函数

带有Twitter API的jquery $ .post有效,但回调函数未返回数据

LLDB:Python API和为观察点设置回调函数

在Laravel api.php文件中找到代码Route :: middleware('auth:api')-> get('/ user',函数(Request $ request)...它的目的是什么?

Node.js中的http.request超时回调

错误:在从API网关的lambda函数请求中解压缩request.body对象时,字符串索引必须为整数

DLL(Windows API)中的回调?

为什么BitBucket OAuth request_token API总是返回400“无法验证OAuth请求”?

事件API的request_token方法未返回请求令牌