javascript - 使用函数从 REST API 获取值

标签 javascript node.js rest

我正在尝试创建一个使用nodeJS 和express、request 返回REST API 响应的函数。 这是我的代码片段:

var express = require('express')
var httpRequest = require('request');
var bodyParser = require('body-parser');
var app = express() 

function getData1() {

    request('http://www.my-server.com/data', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        return body;
      }
    })
} 

app.get('/get-data', function (request, response) {
    var data1 = getData1();

    //do something with data


  response.send(data1);
});

你知道我该怎么做吗?

致以诚挚的问候

最佳答案

由于 getData1 包含一个异步函数,该函数仅在完成时返回数据,只需向其中传递一个回调函数,您将在异步函数完成时调用该函数

// callback -> the function you will call later
function getData1(callback) {

    request('http://www.my-server.com/data', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        // call the function when the function finishes and also passed the `body`
        return callback(body);
      }
    })
} 


app.get('/get-data', function (request, response) {
    getData1(function(data1) {
        //do something with data
        response.send(data1);
    })
});

关于javascript - 使用函数从 REST API 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41891725/

相关文章:

node.js - 无法在 nodejs 中导入 @tensorflow/tfjs-node

javascript - Vuex/Vuejs : accessing localStorage within vuex store

PHP 相当于 Javascript "with"作用域语句

node.js - Node-amqp - 在 X 次尝试后拒绝消息

node.js - 哪个 Azure 选项适合使用 Node.js 的 TCP 游戏服务器?

rest - 金融科技/银行应用程序上可能的 API 授权技术

javascript - 透明背景进度条?

javascript - jshint - 创建自定义警告/规则

rest - 如何使用 Flutter dart 使用 Rest API 登录

.net - 使用 .NET 4 客户端配置文件使用 REST 服务