I'm using axios in an application Nextjs where I use the Youtube API and the following error occurred
Below is the code
import React from "react";
import youtube from "./api";
import VideoList from "./VideoList";
class App extends React.Component {
state = {
videos: [],
};
componentDidMount() {
this.onTermSubmit("Car");
}
onTermSubmit = async (term) => {
const res = await youtube.get("/search", {
params: {
q: term,
},
});
this.setState({ videos: res.data.items });
};
render() {
return (
<>
<div>
<div >
<VideoList
videos={this.state.videos}
/>
</div>
</div>
</>
);
}
}
export default App;
The other
import axios from 'axios';
const KEY = "xxxxx";
export default axios.create({
baseURL: "https://www.googleapis.com/youtube/v3",
params: {
part: "snippet",
maxResults: 16,
key: KEY,
},
});
I would like a tip on how to solve this and if the best solution would be to change from Axios to fetch. Problem is, I don't know how to change from Axios to fetch.
I dont think that is related to package. Because 403 is forbidden response status code which indicates that the server understands the request but refuses to authorize it. Most likely you pass the wrong api key. If you need to fetch the data with fetch, you can write a reusable function:
// genre is like video type. for example Productivity
const videos = async (genre) => {
const YOUTUBE_API_KEY = process.env.YOUTUBE_API_KEY;
const BASE_URL = "youtube.googleapis.com/youtube/v3";
const response = await fetch(
`https://${BASE_URL}/${genre}&maxResults=25&key=${YOUTUBE_API_KEY}`
);
return await response.json();
};
this is from docs
If you're getting a 401 or 403 error when testing a sample, it's likely due to a problem with one of the following:
Downgrade to AXIOS 0.26.0
Probably you are using last version automatically.