使用 Symfony 作为后端并出现 CORS 错误

问题描述

从我的 React 前端向我的 Symfony 后端发送一个请求。(以前它在纯 PHP 后端运行良好)。

useEffect(() => {
              axios.get('http://localhost:8080/real_estate_refactored_backend/main').then((response) => {
                console.log(response);
            })
            .catch((error) => {
                console.log(error.message);
            });
  });

URL 中的 main 是我的 Symfony 控制器的路由

<?PHP

namespace App\Controller;

use App\Entity\Estates;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class MainController extends AbstractController
{
    /**
     * @Route("/main",name="main")
     */
    public function index(): Response
    {
        $entityManager = $this->getDoctrine()->getManager();
        $estates = $entityManager->getRepository(Estates::class)->findAll();

        $response = new Response();
   

    $response->setContent(json_encode([
        'estates' => uniqid(),]));

    $response->headers->set('Content-Type','application/json');
  
    $response->headers->set('Access-Control-Allow-Origin','*');
    return new Response($response);
    }
}

在 Symfony 中,与数据库的连接正常。

尽管我已经在 Symfony 中安装了 Nelmino CORS 包,并在

nelmino_cors.yaml

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

我仍然收到以下错误消息

enter image description here

我能做什么?

解决方法

假设您已将 Symfony(安全)配置为使用会话 cookie 进行身份验证,将 allow_credentials: true 添加到 nelmio_cors.yaml,并将 withCredentials: true 添加到 axios 配置对象:

config/packages/nelmio_cors.yaml

nelmio_cors:
    defaults:
        allow_credentials: true
        # Your existing configuration...

您的 axios 代码段

axios.get('/foo',{ withCredentials: true });
,

您需要将此代码添加到.env

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^.*$
###< nelmio/cors-bundle ###