为什么使用 axios 发出 get 请求失败,状态码为 503?

问题描述 投票:0回答:2
const { default: Axios } = require("axios");
var giveMeAJoke = require("give-me-a-joke");

const getjoke = async () => {
  try {
    const data1 = await Axios.get("https://icanhazdadjoke.com", {
      headers: {
        Accept: "application/json",
      },
    });
  } catch (e) {
    console.log(e);
  }
};

getjoke();

这就是我在 axios 上尝试的。我用 fetch() 提出了相同的请求,并且效果很好。我正在使用的软件包很少依赖于 axios,并且每个软件包都会抛出完全相同的错误。帮帮我吧。

node index.js 
Error: Request failed with status code 503
    at createError (D:\web-technology\practice\test\jokester\node_modules\axios\lib\core\createError.js:16:15)
    at settle (D:\web-technology\practice\test\jokester\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (D:\web-technology\practice\test\jokester\node_modules\axios\lib\adapters\http.js:236:11)
    at IncomingMessage.emit (node:events:406:35)
    at endReadableNT (node:internal/streams/readable:1329:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
javascript node.js ajax https axios
2个回答
3
投票

服务器似乎需要自定义

User-Agent
标头,并且 axios
("axios/0.21.1")
的情况下的默认值会产生问题,因为
axios
后跟
/
符号,所以如果您提供其他值或删除
/
字符例如。
("axios 0.21.1")
,然后就可以了。

const axios = require('axios').default;

const getjoke = async () => {
  try {
    const response = await axios.get("https://icanhazdadjoke.com/", {
      headers: {
        Accept: "application/json",
        "User-Agent": "axios 0.21.1"
      }
    });
    console.log("received response: ", response.data);
  } catch (err) {
    console.log("received error: ", err.toJSON());
  }
};

getjoke();

输出:

received response: {
  id: 'm3wPZoz51ob',
  joke: 'Did you hear the news? FedEx and UPS are merging. They’re going to go by the name Fed-Up from now on.',
  status: 200
}

0
投票

关闭VPN或将其设置为黑名单模式。

© www.soinside.com 2019 - 2024. All rights reserved.