【发布时间】:2020-05-28 04:06:34
【问题描述】:
我正在尝试将 adsense 放在我通过 react 构建的网页上。 自动广告工作正常,但手动广告在我的开发环境和生产环境中都会返回 CORS 错误。
Access to script at 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js' from origin 'http://localhost:3050' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我将脚本标签放在 index.html 中。
<!DOCTYPE html>
<html lang="ko">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=xxxxxxxx"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'xxxxxxxx');
</script>
<script crossorigin async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<meta charset="utf-8" />
<title>Title</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
而jsx文件是这样的。
import React, { useEffect } from 'react';
import Grid from '@material-ui/core/Grid'
const MyPage = (props) => {
useEffect(() => {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}, []);
return (
<Grid
container
justify="center"
>
<Grid item xl={3} lg={2}>
<div style={{
display: 'flex',
justifyContent: 'center',
minWidth: 160,
maxWidth: 320,
height: '100%',
alignItems: 'center',
flexDirection: 'column'
}}
>
<ins
className="adsbygoogle"
style={{ display: 'inline-block', width: '160px', height: '600px' }}
data-ad-client="xxxxxxxxxx"
data-ad-slot="xxxxxxxxxxx"
/>
</div>
</Grid>
<Grid item xl={3} lg={2}>
<div style={{
display: 'flex',
justifyContent: 'center',
minWidth: 160,
maxWidth: 320,
height: '100%',
alignItems: 'center',
flexDirection: 'column'
>
<ins
className="adsbygoogle"
style={{ display: 'inline-block' }}
data-ad-client="xxxxxxxxxxx"
data-ad-slot="xxxxxxxxxxxx"
data-ad-format="auto"
data-full-width-responsive="true"
/>
</div>
)}
</Grid>
</Grid>
);
};
export default MyPage;
我试过了 Having CORS when using Google Adsense in React Firebase web app 并尝试使用 react-adsense 库。 然而,他们都没有成功。 我坚持了3天。有什么解决办法吗?
【问题讨论】:
-
我唯一能想到的是:如果您还没有安装 Chrome 的 Moesif Orign & CORS Changer 扩展程序并关闭 CORS。如果您仍然在本地被阻止,则问题可能是其他问题,您可以解决任何问题。如果扩展成功阻止您被阻止,您仍然需要进行调整,以便 CORS 不会阻止您的开发中的应用。
-
如果一切都失败了,您可能必须创建中间件,将“Access-Control-Allow-Origin: *”标头应用于服务器的每个响应。
标签: javascript reactjs adsense