【发布时间】:2023-03-16 19:35:01
【问题描述】:
我想通过前端请求访问我的后端,但我总是收到以下错误: 从源“...”访问“...”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源。
我已经尝试使用 Nelmio Bundle 并搜索了不同的地方,但没有任何效果。我主要遵循本教程: https://codereviewvideos.com/course/beginners-guide-back-end-json-api-front-end-2018/video/symfony-4-cors-json-api
我也尝试在我的函数中使用标题,但结果是相同的错误消息:
//Controller
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Access-Control-Allow-Origin', '*');
//nelmio_cors.yaml:
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:
'^/': null
//.env File:
###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^https?://.*?$
###< nelmio/cors-bundle ###
【问题讨论】:
-
检查你的头模块是否启用。如果您使用的是 apache
sudo a2enmod header并使用sudo service apache2 reload重新启动您的 apache 服务器
标签: php symfony cors nelmiocorsbundle