簡體   English   中英

向 API 發出獲取請求時用戶代理丟失錯誤

[英]User Agent Missing error when making a get request to an API

我正在嘗試使用新聞 API 制作項目,但我不斷收到 userAgentMissing 錯誤。 我嘗試了幾件事,但我無法弄清楚我做錯了什么。 我也嘗試過使用 https.request 方法,但結果是一樣的。

app.get("/", function (req, res) {
let url = "https://newsapi.org/v2/top-headlines?country=in&apiKey=xxxxx";

https.get(url, function (response) {
    console.log(response.statusCode);
    response.on('data', function (data) {
        const recievedData = JSON.parse(data);
        console.log(recievedData); 
    });
  });
});

這是我得到的錯誤。

400
{
狀態:'錯誤',
代碼:'userAgentMissing',
消息:'請設置您的用戶代理 header 以識別您的應用程序。 不允許匿名請求。
}

將標頭中的用戶代理作為參數傳遞對我有用。 同樣在使用 fetch 方法時我沒有遇到這個問題。

  app.get("/", function (req, res) {
  const userAgent = req.get('user-agent');
  const options = {
  host: 'newsapi.org',
  path: '/v2/top-headlines?country=in&apiKey=xxxxxxxx',
  headers: {
    'User-Agent': userAgent
  }
}
https.get(options, function (response) {
let data;
  response.on('data', function (chunk) {
      if (!data) {
          data = chunk;
      }
      else {
          data += chunk;
      }
  });
  response.on('end', function () {
      const newsData = JSON.parse(data);
      console.log(newsData);
    });
  });
  res.send("hello");
});

暫無
暫無

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

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