laravelにreactを入れてaxiosを書いて、外部apiにアクセスするとCORSエラーになる場合があります。
原因は、resources/js/bootstrap.js
の
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
です。
以下のようにするとエラーが出ないようになります。
// resources/js/components内のファイルなどで記載
const extAxios = axios.create();
delete extAxios.defaults.headers.common["X-Requested-With"];
function Example() {
useEffect(() => {
extAxios.get("https://aws.random.cat/meow").then((res) => {
console.log(res.data.file);
});
}, []);
// 以下省略