Home > Software engineering >  How to add a header field with value as api key in react axios request
How to add a header field with value as api key in react axios request

Time:04-27

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;

CodePudding user response:

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

CodePudding user response:

here is the use for headers on axios:

 useEffect(() => {
            axios.get("https://challenge.movies.com.au/api/v2/blahblah/movies", {
        headers:{
        'x-api-key': 'Bearer 12345678')
              }
              .then((res) => console.log(res.data))
              .catch((err) => console.log(err));
          }, []);

CodePudding user response:

You can simply pass headers like that

    axios
          .post(
            "url",
            {
              key : value
            },
            {
              headers: {
                Authorization: "Bearer "   JSON.parse(token),
              },
            }
          )
  .then(async (response) => {
       //Handel response here
      })
      .catch((error) => {
        console.log(error);
      });
  • Related