简体   繁体   English

嵌套亲子 REST api 调用 node.js?

[英]nested parent-child REST api call in node.js?

I encountered a situation which requires nested REST api call in node.js when I got routed rest api POST call, then during that POST(parent) need to call REST get call(child) inside of POST call.当我路由 rest api POST 调用时,我遇到了需要在 node.js 中嵌套 REST api 调用的情况,然后在该 POST(父)期间需要调用 REST get call(child.) inside of POST.

I am doing this to merge parent's data with child's data then store it in MongoDB我这样做是为了将父母的数据与孩子的数据合并,然后将其存储在 MongoDB

here's an example..(routes/index.js)这是一个例子..(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

     }
}

have no idea不知道

  1. how to call REST API get call inside with header option(x-api-key sting)如何调用 REST API 使用 header 选项在内部调用(x-api-key sting)
  2. merge get returned data with post inserted data in one object将返回的数据与插入后的数据合并到一个 object

Is there any way to accomplish this?有什么办法可以做到这一点?

You need to have a http request library (like Axios) installed and you make use of that library to make the GET request inside your POST request handler.您需要安装一个 http 请求库(如 Axios),并使用该库在 POST 请求处理程序中发出 GET 请求。 I would advise you make your callback async我建议你让你的回调异步

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);
         }
     }
}

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

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