簡體   English   中英

在 Next.js API 路由中進行外部 API 調用時遇到錯誤

[英]Encountered error when making external API call in Next.js API Route

我正在 next.js 中編寫一條 API 路由,它將調用 GitHub ZDB974238714CA8DE634A7CE1D083A 並返回我的用戶 GitHub1 響應。 我的 API 本質上是一個代理。 但是,我在終端中的服務器因Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client而崩潰。 我究竟做錯了什么? 感謝您的幫助,謝謝!

const https = require('https')

export default (req, res) => {
  const options = {
    host: 'api.github.com',
    path: '/search/repositories?q=tetris',
    headers: {'user-agent': 'gohyifan'}
  }
  https.get(options, (ghRes) => {
    ghRes.on('data', (d) => {
      res.json(d);
    });
  }).on('error', (e) => {
    console.error(e);
  });
}

我用 axios 做到了,它奏效了。 線程可以關閉。

const axios = require('axios');

async function handler(req, res) {
  const response = await axios.get('https://api.github.com/search/repositories?q=tetris');
  if (response) {
    res.json(response.data);
  } else {
    res.json({});
  }
}

export default handler;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM