gpt4 book ai didi

php - 在 symfony 4 上允许 CORS

转载 作者:行者123 更新时间:2023-12-03 23:21:26 25 4
gpt4 key购买 nike

我最近需要允许 CORS 并在寻找解决方案时找到 nelmio/NelmioCorsBundle .

对于乞讨,我可以允许来自任何来源的请求,所以这是我的 app/config/config.yml :

nelmio_cors:
defaults:
allow_credentials: false
allow_origin: ['*']
allow_headers: ['*']
allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
max_age: 3600
origin_regex: false

它仅适用于 GET 请求,任何 POST 请求都会返回:

No 'Access-Control-Allow-Origin' header is present on the requested resource.



我不一定需要使用这个包,在乞讨时我试图取消注释 TRUSTED_HOSTS并将其设置为我的域 dotenv文件,但它没有用。此外,我没有在文档中找到有关此 TRUSTED_HOSTS 的任何帮助。

因此,任何有关此捆绑包或 symfony 上 CORS 的任何其他解决方案的任何帮助,我都会很高兴。

按照我的要求,我正在更新我当前的 nelmiocors 配置:
# app/config/config.yml

# Nelmio CORS Configuration
nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
paths:
'^/':
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
# allow_origin: ['^http://localhost:[0-9]+']
allow_headers: ['*']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
# allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600
# hosts: ['^api\.']

最佳答案

不知道到底出了什么问题,但是因为其中一条评论有所帮助(帮助的人可能已经删除了自己的评论)。

我最终对 Nelmio CORS 进行了此配置:

nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['*']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
paths:
'^/': ~

然后从 cli 和手动清除缓存,它工作了。

我猜我做错了什么:当我第一次配置 Nelmio CORS 时,我没有清除缓存,因此它不起作用。之后我尝试了一些其他的配置组合,即使我清除了缓存,它也不起作用。这让我觉得如果我没有忘记清除缓存,代码应该可以工作,在此之后我使用了无效的配置并且显然清除缓存这是行不通的。总之,这是一个初学者的错误。

关于php - 在 symfony 4 上允许 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54544855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com