[英]How to use router.get and https.get together? (Node.js)
我想從 http 請求中獲取信息,並通過路徑“/get”將其發送到前端。 我結合了這兩個功能,它可以工作,但我認為它不正確:
const router = express.Router();
const https = require('https');
router.get('/get', (req, res) => {
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
res.json(JSON.parse(data).explanation)
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
});
有一個更好的方法嗎?
不,它工作正常。
但是如果你想要另一種方式,那么使用axios
您需要要求
axios
然后在路由器中添加您的請求。
const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345').then(function (response) { // handle success console.log(response); }).catch(function (error) { // handle error console.log(error); }).then(function () { // always executed });
你可以從這里獲得更多信息
更好的方法是使用Axios將您的所有 http 請求發送到您希望從 nodejs 應用程序獲得的外部 api。 它是一個基於 promise 的請求制作庫,您可以在瀏覽器和后端服務器上使用它。
axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY').then(response => res.send(response.data)).catch(error => console.log(error));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.