我有一个使用多种路由创建的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 的方法,但只是感到困惑。
非常感谢您提供的任何帮助!
我建议使用axios https://github.com/axios/axios如果你想调用第三方API。简单的方法是创建一个选项(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
详细信息在上面的链接中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)