Answer the question
In order to leave comments, you need to log in
Symfony 4 REST API: how to properly enable OPTIONS method?
There is a client, there is a server. Server is API, client is JS.
The client makes a request to the API via AJAX, the first request is OPTIONS, but only the GET and POST methods are registered in the API routes (depending on the request), but for all routes, the OPTIONS request goes first, which of course does not pass the test.
PHP Fatal error: Uncaught Symfony\Component\Routing\Exception\MethodNotAllowedException
Just adding the OPTIONS method to all routes solves the problem, but it's not a solution, because in this case both OPTIONS + GET requests are fully processed, which is not good, because OPTIONS should not do anything and should just return one headers with an empty response.
How to properly enable OPTIONS?
Adding in headers to response Access-Control-Allow-Methods: GET, POST, OPTIONS does not work
Answer the question
In order to leave comments, you need to log in
In the simplest case, you can move the handling of OPTIONS to a separate method:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/blog")
*/
class BlogController extends AbstractController
{
/**
* @Route("/", methods="OPTIONS")
*/
public function options(Request $request): Response
{
$response = new Response();
$response->headers->set('Access-Control-Allow-Methods', 'OPTIONS, GET');
return $response;
}
/**
* @Route("/", methods="GET", name="blog_index")
*/
public function index(Request $request): Response
{
return $this->json([
'message' => 'hello',
]);
}
}
https://github.com/nelmio/NelmioCorsBundle
Note: read what CORS is; why these requests generally fly away; what are the CORS scripts.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question