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

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

我有一个 express.js REST API,我用各种路由创建了它。我想创建一个路由来调用另一个 REST API 然后 return 结果。理想情况下,它应该类似于以下内容:

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 正文。然后它将 return 包含票证信息和票证的 JSON 响应 link.

本质上,我只想将 req.body 作为 API 调用的主体传递,然后 res.send() 作为 API 调用的响应。我试图找出一些使用 fetch 或 requests 的方法,但只是感到困惑。

非常感谢您提供任何帮助!

你必须使用类似 axios 或 http 的东西(代码来自 link):

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

如果你想调用第三方API,我建议使用axios。简单的方法是创建一个选项(配置)将其传递给 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,它会发回响应。您可以查看上面 link 中的 axios 详细信息。