LoginSignup
0
0

More than 3 years have passed since last update.

ReactでAPIを呼び出したところ、CORSエラーが発生。その対処方法

Posted at

ReactでpixabayのAPIを使って画像検索アプリケーションを作成した際にCORSエラーが発生

エラー内容

Access to XMLHttpRequest at 'https://pixabay.com/api/?q=animal' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

エラーの発生経緯


const App =()=>{
  const [images, setImages]= useState([]);
  const ApiKey = process.env.REACT_APP_PIXABAY_APIKEY;
  const onSearchSubmit =async(term)=>{
    try{
      const params={
        key: ApiKey,
        q: term,
      };
      const response= await axios.get('https://pixabay.com/api/', { params });
      setImages(response.data.hits);

上記のようにAPIキーを環境変数に記述し、App.jsに引き渡す処理を実装した際に発生。
色々と検索してみた結果以下の記事を発見、参考にしてみました。

なんとなく CORS がわかる...はもう終わりにする。

なるほど。セキュリティ上の問題か〜賢い!そしておもしろい!
参考にしていじってみよう。

そして10年後・・・・(冗談)

サーバーを再起動したら解決

いろいろと試行錯誤した結果、「まさか!」と思い、
control+cして、yarn startしたところ、普通に解決しました。
なぜだ・・・。

一日中サーバー起動しっぱなしで作業してたからですかね?
詳しい方、教えていただけますと幸いです。。。

再起動したら改善されることは、よくあることなので覚えておこう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0