Search code examples
reactjsreact-nativeaxiosgetrequest-headers

How to add a header field with value as api key in react axios request


To access my api I need to add a header field: x-api-key to the axios get request with the value as the api key: 12345678. How can I do this in react with my current code?

import "./App.css";
import axios from "axios";
import { useEffect } from "react";

function App() {
  useEffect(() => {
    axios
      .get("https://challenge.movies.com.au/api/v2/blahblah/movies")
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));
  }, []);

  return <div className="App"></div>;
}

export default App;

Solution

  • Try this.

        const AuthStr = 'Bearer '.concat(USER_TOKEN); 
        axios.get(URL, { headers: { Authorization: AuthStr } })
         .then(response => {
             // If request is good...
             console.log(response.data);
          })
         .catch((error) => {
             console.log('error ' + error);
          });