簡體   English   中英

如何使用 axios header 獲取數據?

[英]How to fetch the data from using axios header?

我正在嘗試使用 axios 獲取 json 數據。 你能告訴我我在這里做錯了什么嗎

我也嘗試過使用鈎子來做,但無濟於事。 我把它放在基於 class 的組件下面,請看一下。 你能告訴我我在這里做錯了什么嗎

API: https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY

API_KEY:3055f8f90fa44bbe8bda05385a20690a

      import React, { Component } from "react";
        import axios from "axios";
        import Post from "../../Component/Post/Post";
        
        export default class Home extends Component {
          state = {
            posts: [],
          };
        
          componentDidMount() {
            axios
              .get(
                "https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY",
                {
                  headers: {
                    " API_KEY ": "3055f8f90fa44bbe8bda05385a20690a",
                  },
                }
              )
              .then((response) => {
                console.log(response.data);
                this.setState({ posts: response.data });
              })
              .catch((err) => {
                console.log("API call error:", err.message);
              });
          }
          render() {
            const posts = this.state.posts.map((post) => {
              return <Post key={post.id} />;
            });
            return <div>{posts}</div>;
          }
        }




import React, { useState, useEffect } from "react";
import Post from "../../Components/Post/Post";
import axios from "axios";

const HomePage = () => {
  const [posts, setPosts] = useState("");

  let config = { Authorization: "3055f8f90fa44bbe8bda05385a20690a" }; //3055f8f90fa44bbe8bda05385a20690a
  const url =
    "https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY";

  useEffect(() => {
    AllPosts();
  }, []);

  const AllPosts = () => {
    axios
      .get(`${url}`, { headers: config })

      .then((response) => {
        const allPosts = response.data;

        setPosts(allPosts);
      })
      .catch((error) => console.error(`Error: ${error}`));
  };

  return (
    <div>
      <Post className="Posts" posts={posts} />
    </div>
  );
};

export default HomePage;

用這個替換你以前的代碼:

let config = {'Authorization': 'MY-API-KEY'};//3055f8f90fa44bbe8bda05385a20690a
axios.get('https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY', {headers: config})

另外,參考這個問題來深入理解這個問題: Setting authorization header in axios

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM