router.get 和 https.get 如何一起使用? (Node.js)

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

you need to require axios and then add your request in the router.

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

您从 here

获得更多信息

更好的方法是使用 Axios 将所有 http 请求发送到您希望来自 nodejs 应用程序的外部 api。这是一个基于承诺的请求制作库,您可以在浏览器和后端服务器上使用它。

  1. 使用 npm install axios
  2. 安装 axios
  3. axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY').then(response => res.send(response.data)).catch(error => console.log(error));