如何在react axios请求中添加一个值为API键的头字段

wqlqzqxt  于 2023-03-02  发布在  iOS
关注(0)|答案(3)|浏览(155)

要访问我的API,我需要添加一个头字段:x-api-key到axios get请求,其值作为api密钥:12345678。如何在对当前代码的响应中执行此操作?

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;
vi4fp9gy

vi4fp9gy1#

试试这个。

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

zvokhttg2#

下面是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));
          }, []);
mrfwxfqh

mrfwxfqh3#

您可以简单地像这样传递标头

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

相关问题