簡體   English   中英

嵌套親子 REST api 調用 node.js?

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

當我路由 rest api POST 調用時,我遇到了需要在 node.js 中嵌套 REST api 調用的情況,然后在該 POST(父)期間需要調用 REST get call(child.) inside of POST.

我這樣做是為了將父母的數據與孩子的數據合並,然后將其存儲在 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 使用 header 選項在內部調用(x-api-key sting)
  2. 將返回的數據與插入后的數據合並到一個 object

有什么辦法可以做到這一點?

您需要安裝一個 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);
         }
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM