How can I fetch data from yelp api in React JS?

2k views Asked by At

I want to fetch data from Yelp API in react JS. I can fetch data using postman but I am unable to fetch any data with my code. Here is the code.

 componentDidMount = () => {
const API_BASE_URL =
  'https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/business/search?term=restaurant&location=usa';
const BEARER_TOKEN =
  'mybearertoken';

fetch(`${API_BASE_URL}`, {
  headers: {
    Authorization: `${BEARER_TOKEN}`,
    Origin: 'localhost:3000',
    withCredentials: true,
  },
})
  .then(res => res.json())
  .then(json => {
    this.setState({
      isLoaded: true,
      items: json,
    });
  });

};

2

There are 2 answers

1
Rain.To On

try

headers: {
      'Content-Type': 'application/json'          
    }
0
Ashenafi Semu On

I npm installed and used Axios and it worked.

const fetchtems = async () => {
const data = await axios
  .get(
    `${'https://cors-anywhere.herokuapp.com/'}https://api.yelp.com/v3/businesses/search?location=usa`,
    {
      headers: {
        Authorization: `Bearer ${BEARER_TOKEN}`,
      },
      params: {
        term: 'restaurants',
      },
    },
  )

  .then(json => {
    setItems({ items: json.data.businesses });
  })
  .catch(err => {
    console.log(err);
  });

};