【问题标题】:HTTP get request with Axios gets sent with the local host IP at the beginning of the URL使用 Axios 的 HTTP 获取请求在 URL 的开头使用本地主机 IP 发送
【发布时间】:2018-08-04 06:09:03
【问题描述】:

我正在尝试使用 Axios 发送 HTTP 请求,但收到 404 错误。原因是请求在 URL 的开头使用本地主机 IP 发送,为什么会发生这种情况?

JS:

function getWeather() {

  axios.get('api.openweathermap.org/data/2.5/weather', {
    params: {
      lat: 30.18,
      lon: 30.87,
      appid: '57d9478bc08bc211f405f45b93b79272'
    }
  })
  .then(function(response) {
    console.log(response);
  })

  .catch(function(error) {
    console.log(error);
  })
};
getWeather();  

错误:

http://127.0.0.1:5500/api.openweathermap.org/data/2.5/weather?lat=30.18&lon=30.87&appid=57d9478b#####################3b79272 404 (Not Found)

【问题讨论】:

    标签: javascript http axios


    【解决方案1】:

    在 Axios 的 URL 参数中,您没有指定用于 API 请求的协议(可能是 HTTP)。因此,Axios 将其解释为相对 URL 路径并添加本地服务器的路径,因为它需要完整的 URL 才能发出请求。

    您可以通过添加 http:// 前缀轻松修复它:

    axios.get('http://api.openweathermap.org/data/2.5/weather', {
    

    【讨论】:

      【解决方案2】:

      您可以在请求之前配置 axios 基本 url

      axios.defaults.baseURL = 'http://api.openweathermap.org';
      axios.get('/data/2.5/weather')
      

      【讨论】:

      • axios.defaults.baseURL 如果您要将 axios 导出为 axios.create .....
      【解决方案3】:

      要完全控制 axios 的基本 URL,您可以在 AxiosInstance 创建时指定 baseURL

          var getBaseUrl = () => {
              // custom base URL logic examples:
              // - to request a current URL without the search parameters part:
              let baseUrl = window.location.href.slice(0, -window.location.search.length);
      
              //// or to insert '/api' after the host part
              //let baseUrl = window.location.host + '/api' + window.location.pathname;
      
              // ensure slash at the end
              if (baseUrl[baseUrl.length - 1] != '/') baseUrl = baseUrl + '/';
      
              return baseUrl;
          };
      
          var axiosConfig = {
              baseURL: this.getBaseUrl(),
          };
          var axiosInstance = axios.create(axiosConfig);
      
          axiosInstance.get('/your-path')
             .then(res => {
                 // ...
             });
             // ...
      

      【讨论】:

        猜你喜欢
        • 2021-08-20
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多