簡體   English   中英

如何在快速路由中調用不同的 REST API?

[英]How do I call a different REST API within a express route?

我有一個 express.js REST API,我用各種路由創建了它。 我想創建一個路由來調用另一個 REST API,然后返回結果。 理想情況下,它應該如下所示:

router.post('/CreateTicket', cors(corsOptions), function(req, res, next) {
   //make a call to another rest api and then res.send the result
}

我正在調用的 REST API 路由是一個 POST 請求,它將接收帶有票證信息的 JSON 正文。 然后它將返回一個包含票證信息和票證鏈接的 JSON 響應。

本質上,我只想傳遞 req.body 作為 API 調用的主體,然后 res.send() 傳遞 API 調用的響應。 我試圖找出某種使用 fetch 或 requests 的方法,但只是感到困惑。

非常感謝您提供任何人都可以提供的幫助!

如果你想調用第三方 API,我建議使用axios 這樣做的簡單方法是創建一個 options(config) 將它傳遞給 axios 對象。

npm i axios --save 

axios 配置

  const options = {
    'method': 'POST',
    'url': 'https://URL',
    'headers': {
      'Content-Type': 'application/json'
    },
    data: {
       firstName: 'Fred',
       lastName: 'Flintstone'
    }
  };

  try {
    const result = await axios(options);
    console.log(result);
  } catch (e) {
       console.log(e);
  }
  

在您的路線文件中:

const axios = require('axios');


const getData = async (body) => {
      const options = {
    'method': 'POST',
    'url': 'https://URL',
    'headers': {
      'Content-Type': 'application/json'
    },
    data: {
      body
    }
  };

  try {
    const result = await axios(options);
    console.log(result);
    return result;
  } catch (e) {
       console.log(e);
  }
}

router.post('/CreateTicket', cors(corsOptions), async function(req, res, next) {
   //make a call to another rest api and then res.send the result
  try {
    const response = await getData(req.body);
   res.send(response);
  } catch (e) {
    //wrap your error object and send it
  }
   
}

注意:如果您想將數據傳遞到您自己創建的路由,您可以使用res.redirect ,它會將響應發回。 您可以在上面的鏈接中查看axios詳細信息。

您必須使用 axios 或http 之類的東西(代碼來自鏈接):

 const https = require('https') const options = { hostname: 'example.com', port: 443, path: '/todos', method: 'GET' } const req = https.request(options, res => { console.log(`statusCode: ${res.statusCode}`) res.on('data', d => { return d }) }

暫無
暫無

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

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