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



我有一个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响应,其中包含票证信息和票证链接。

本质上,我只是想通过请求。body作为API调用的主体,然后res.send()作为API调用的响应。我试图找出一些方法来使用fetch或请求,但只是有点困惑。

非常感谢任何人可以提供的任何帮助!

如果你想调用第三方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,它会发送响应回来。您可以在上面的链接中查看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
})
}

最新更新