我有一個 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 的方法,但只是感到困惑。
非常感謝您提供任何人都可以提供的幫助!
uj5u.com熱心網友回復:
如果你想呼叫第三方 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在上面的鏈接中查看詳細資訊。
uj5u.com熱心網友回復:
您必須使用 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
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/328933.html
