【问题标题】:Axios get request format for third party apiaxios获取第三方api的请求格式
【发布时间】:2021-12-07 18:59:27
【问题描述】:

我目前正在开发一个天气应用程序,并正在使用 Axios 执行对第三方天气 API 的获取请求。当我在 Postman 上执行 API 请求时,我能够检索所需的数据但是当我使用 Axios 执行此请求时,我收到 400 bad request 错误。我浏览了 Axios 文档以查看我的格式是否存在问题,但我发现他们的文档和我的代码没有差异。我已经为此工作了几个小时,我很难过你们是否发现我的代码有任何问题可能导致此错误。

这是我的代码

app.get("/weatherquery/:zip", (req, res) => {
  axios({
    url: "api.openweathermap.org/data/2.5/weather?zip=08060&appid=[CHANGE_FOR_YOUR_APPID]",
  })
    .then((result) => res.send(result))
    .catch((error) => {
      console.log(error);
      res.send(error.message);
    });
});

这就是错误

400
{ connection: 'close' }
{
  transitional: {
    silentJSONParsing: true,
    forcedJSONParsing: true,
    clarifyTimeoutError: false
  },
  adapter: [Function: httpAdapter],
  transformRequest: [ [Function: transformRequest] ],
  transformResponse: [ [Function: transformResponse] ],
  timeout: 0,
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
  maxContentLength: -1,
  maxBodyLength: -1,
  validateStatus: [Function: validateStatus],
  headers: {
    Accept: 'application/json, text/plain, */*',
    'User-Agent': 'axios/0.23.0'
  },
  url: 'api.openweathermap.org/data/2.5/weather?zip=08060&appid=73faabe2b55b90dc0d0c89c4899b2a94',
  method: 'get',
  data: undefined
}

【问题讨论】:

    标签: javascript api axios get


    【解决方案1】:

    检查网址中的https://

    var axios = require('axios');
    
    var config = {
      method: 'get',
      url: 'https://api.openweathermap.org/data/2.5/weather?zip=08060&appid=[CHANGE_FOR_YOUR_APPID]',
      headers: { }
    };
    
    axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });
    

    【讨论】:

    • 这确实有效,非常感谢!
    【解决方案2】:

    只要 API 在 Postman 中有效,但在网页中无效,很可能是因为 CORS 问题。作为安全预防措施,浏览器会阻止发出“跨站点”请求……例如。从 yourdomain.com 到 openweathermap.org 的请求。

    如果 openweathermap.org 以某种方式提供 CORS 支持(或 JSONP 和旧解决方案),您仍然可以访问它。否则,您将需要某种可以充当“代理”的服务器(即,您向同一域中的服务器发出请求,然后它向天气 API 发出请求)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多