Having CORS when using Google Adsense in React Firebase web app

折月煮酒 提交于 2019-12-13 17:23:13

问题


I want to add google adsense to my react web. I am using the library react-adsense.

However, I got this error while I want to add the google adsense script in my html file:

Access to Script at 'http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Here is how I added the script:

<script crossorigin="anonymous" async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Update #1 I am using firebase to host my website


回答1:


To test Adsense locally you may try one of these options:

1- use data-adtest="on"

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<ins class="adsbygoogle"
 data-adtest="on"></ins>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({});
</script>

2- Use google_adtest="on"; (synchronous)

<script type="text/javascript">google_adtest="on";</script>
<script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

3- Use an extension (chrome example) like this one. Or try another browser.

4- If none works, you may try doing a reverse proxy with proxy_pass in nginx - in order to "simulate" that you are visiting from an allowed origin and editing your /etc/hosts (not sure it works though).

server {
  listen       80;
  server_name  mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}


来源:https://stackoverflow.com/questions/49347921/having-cors-when-using-google-adsense-in-react-firebase-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!