-1

I'm trying to fetch the json data using axios. Could you please tell me what am i doing wrong here

I have tried doing it using hooks as well but to no avail. i have put it below the class based component please have a look at it. Could you please tell me what am i doing wrong here

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;
sud
  • 45
  • 6
  • Could you, please, describe a bit more in-depth what issue you are facing exactly? It'd also help if you provided a shorter snippet of your code, specifically the part where you think the issue is boiling down to. – almarc Apr 28 '21 at 11:57
  • The issue has been resolved. Thanks for your help – sud Apr 28 '21 at 12:38

1 Answers1

2

Replace your previous codes with this:

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

Also, refer to this question to get a deep understanding of the problem: Setting authorization header in axios

Blessing
  • 2,450
  • 15
  • 22
  • Thanks, Where should i define the APIKEY? – sud Apr 28 '21 at 10:21
  • replace `MY-API-KEY` with the original key. it'll be `let config = {'Authorization': '3055f8f90fa44bbe8bda05385a20690a'};` – Blessing Apr 28 '21 at 10:22
  • DOMException: Invalid header name. – sud Apr 28 '21 at 10:24
  • i even tried doing it using hooks its showing either dom expection error or Request failed with status code 401 @Blessing – sud Apr 28 '21 at 11:05
  • since it's a `401 error` you have to check whether your `API KEY` is valid. – Blessing Apr 28 '21 at 11:14
  • https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=3055f8f90fa44bbe8bda05385a20690a It is valid when i run its working fine. But when i put the same in code its throwing those errors. Could you please check my the hooks code? – sud Apr 28 '21 at 11:21
  • The URL should not include apiKey. It should only be https://newsapi.org/v2/top-headlines?sources=bbc-news – sud Apr 30 '21 at 11:54