带有axios的http get请求使用url上的本地主机ip发送它

时间:2018-02-24 07:34:51

标签: javascript http axios

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

JS:

 #include "stdafx.h"
#include <string>
#include <iostream>
#include <cctype>
#include <cstring>


using namespace std;

// Function Prototypes
void upperFunct(char *);
void lowerFunct(char *);
void reverseFunct(char *);


int main()
{
cout << "Enter a string: " << endl;
char ltrs [300];
cin.getline(ltrs, 300);
char *ptr = nullptr;
ptr = ltrs;

upperFunct(ptr);
lowerFunct(ptr);
reverseFunct(ptr);  

return 0;
 }
//----------------------------------//
void upperFunct(char *ltrptr)
{
int count = 0;
while (ltrptr[count] != '\0')
{
ltrptr[count] = toupper(ltrptr[count]);
count++;
}
{
    cout << "---> toupper function: " << ltrptr << endl;
}
}
//------------------------------------//
void lowerFunct(char *ltrptr)
{ 
int count = 0;
while (ltrptr[count] != '\0')
{
ltrptr[count] = tolower(ltrptr[count]);
count++;
}
cout << "---> tolower function: " << ltrptr << endl;
}
//------------------------------------//
void reverseFunct(char *ltrptr) // <-----NOT REVERSING CHARACTERS 
{
int count = 0;

while (ltrptr[count] != '\0')
{
    if (isupper(ltrptr[count]))
    {
        ltrptr[count] = tolower(ltrptr[count]);
    }
    else
    {
        ltrptr[count] = toupper(ltrptr[count]);
    }
    count++;
}
cout << "---> reverse function: " << ltrptr << endl;
}

ERROR:

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();  

3 个答案:

答案 0 :(得分:5)

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

您可以通过添加http://前缀:

轻松修复它
axios.get('http://api.openweathermap.org/data/2.5/weather', {

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

    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 => {
           // ...
       });
       // ...
相关问题