如何在 Netlify 部署中启用 CORS?
How to enable CORS on a Netlify deployment?
我正在使用 Netlify 提供一些静态 .json
文件。它们在浏览器中加载正常,但是当我尝试通过 javascript 获取它们时,我在控制台中收到以下错误:
Access to fetch at (redirected from ) from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
我在 Netlify 仪表板中检查了我网站设置中的所有选项,但没有看到任何启用 CORS 的选项,这怎么办?
在您的 index.html 旁边添加一个名为 _headers
的文件,内容如下:
/*
Access-Control-Allow-Origin: *
最好将其更改为您的实际来源,而不是 *
在生产中。
更好的方法是使用这样的代理,
在项目的根目录中创建一个名为 netlify.toml
的文件。 (即 index.html
旁边)
[[redirects]]
from = "/<path-to-access-cors-url>"
to = "<cross-origin-url>"
status = 200
force = true
headers = {X-From = "Netlify"}
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
现在像这样在 HTTP 请求中使用 URL,https://your-domain.com/<path-to-access-cors-url>
示例:
考虑一下,fakedomain.com
是您的域,您想从 https://example.com/patha
请求资源
[[redirects]]
from = "/pathx"
to = "https://example.com/patha"
status = 200
force = true
headers = {X-From = "Netlify"}
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
现在像这样在 HTTP 请求中使用 URL,https://fakedomain.com/pathx
我正在使用 Netlify 提供一些静态 .json
文件。它们在浏览器中加载正常,但是当我尝试通过 javascript 获取它们时,我在控制台中收到以下错误:
Access to fetch at (redirected from ) from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我在 Netlify 仪表板中检查了我网站设置中的所有选项,但没有看到任何启用 CORS 的选项,这怎么办?
在您的 index.html 旁边添加一个名为 _headers
的文件,内容如下:
/*
Access-Control-Allow-Origin: *
最好将其更改为您的实际来源,而不是 *
在生产中。
更好的方法是使用这样的代理,
在项目的根目录中创建一个名为 netlify.toml
的文件。 (即 index.html
旁边)
[[redirects]]
from = "/<path-to-access-cors-url>"
to = "<cross-origin-url>"
status = 200
force = true
headers = {X-From = "Netlify"}
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
现在像这样在 HTTP 请求中使用 URL,https://your-domain.com/<path-to-access-cors-url>
示例:
考虑一下,fakedomain.com
是您的域,您想从 https://example.com/patha
[[redirects]]
from = "/pathx"
to = "https://example.com/patha"
status = 200
force = true
headers = {X-From = "Netlify"}
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
现在像这样在 HTTP 请求中使用 URL,https://fakedomain.com/pathx