简体   繁体   中英

How can I convert from Fetch to axios? I get 401 error

I need to write coding with Axios. But the example of API documentation is with fetch. When I convert Axios I get a 401 error.

Fetch

API = "https://api.apilayer.com/exchangerates_data";

    var myHeaders = new Headers();
      myHeaders.append("apikey", API_KEY);
      var requestOptions = {
        method: "GET",
        redirect: "follow",
        headers: myHeaders,
      };
      fetch(`${API}/symbols`, requestOptions)
        .then((response) => response.json())
        .then((result) => {
          setCurrenciesData(result.symbols);
          setLoading(false);
        })
        .catch((error) => setLoading(false));
    };

My friend wrote it with Axios like this and it worked. But when I wrote like this, it gave me same error

axios.get(`${API}/symbols&apikey=${API_KEY}`)

Please try the following code!

axios.get({
  baseURL: API,
  url: "/symbols",
  headers: { apikey: API_KEY },
});

Here you can check all axios request config available params Axios Request Config .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM