【问题标题】:nested parent-child REST api call in node.js?node.js中嵌套的父子REST api调用?
【发布时间】:2021-04-19 07:08:55
【问题描述】:

我遇到了需要在 node.js 中调用嵌套 REST api 的情况 当我收到路由休息 api POST 调用时, 然后在 POST(parent) 期间需要在 POST 调用中调用 REST get call(child)。

我这样做是为了将父数据与子数据合并,然后将其存储在 MongoDB 中

这是一个例子..(routes/index.js)

const variable = require('../app.js');
const { db } = require('../models/user.js');
const async = require('async');
const time_js = require('../time.js');

module.exports = function (app, Transaction_log, User) {
     app.post('/api/transaction_logs', function (req, res) {

          ... get method REST call to certain url(different IP addr) with header option

     }
}

不知道

  1. 如何调用 REST API get call inside with header option(x-api-key sting)
  2. 将获取返回的数据与插入后的数据合并到一个对象中

有没有办法做到这一点?

【问题讨论】:

  • 你没有在那里声明app。我猜这是一个 Express 应用程序
  • @Reger 对不起,我没听懂。我有 app.js 并在那里声明了 app。 :S 是的,它是 var app = express();使用 express 框架
  • 这里的挑战是什么?
  • @Qausim 不知道如何调用 REST API get call inside with header option(x-api-key sting)

标签: javascript node.js express mongoose rest


【解决方案1】:

您需要安装一个 http 请求库(如 Axios),并使用该库在您的 POST 请求处理程序中发出 GET 请求。我会建议你让你的回调异步

module.exports = function (app, Transaction_log, User) {
       app.post('/api/transaction_logs', async function (req, res) {
         try {
           const res = await Axio.get(
             'other URL', {
             headers: {
               // header configurations here
             }
           });
           // extract data
           // merge request body and extracted data
           // save in DB
         } catch (e) {
           console.log(e);
         }
     }
}

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多