2

I am new with GraphQL. I need to make an API with PHP and GraphQL. I followed this tutorial: https://medium.com/swlh/setting-up-graphql-with-php-9baba3f21501

everything was OK, but when opening the URL, I got this error:

{
    "statusCode": 405,
    "error": {
        "type": "NOT_ALLOWED",
        "description": "Method not allowed. Must be one of: OPTIONS"
    }
}

I added this to the index page :

 header('Access-Control-Allow-Origin', '*');
 header('Access-Control-Allow-Headers', 'content-type');
 header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

but the problem wasn't resolved. Maybe something is missing here:

return function (App $app) {
    $app->options('/{routes:.*}', function (Request $request, Response $response) {
        // CORS Pre-Flight OPTIONS Request Handler
        return $response;
    });
Iheb Saad
  • 147
  • 1
  • 2
  • 15

2 Answers2

2

Error Message : Method not Allowed
Error Status Code : 405

Reason :
Actually we get this error as response to our option request not to our Post request. Browser sends option request before it sends POST, PATCH, PUT, DELETE and so on. GraphQL declines anything that is not GET or POST so option request is declined

Solution : Go to our cors middleware and check if its option then returns empty response with status 200. So in this way option request will never reach to GraphQL middleware

Like :

  if (req.method === "OPTIONS") {
    return res.sendStatus(200);
  }

as

  app.use((req, res, next) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Methods",
        "OPTIONS, GET, POST, PUT, PATCH, DELETE"
      );
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
   
     if (req.method === "OPTIONS") {
           return res.sendStatus(200);
     }
     next();
    });
mabdullahse
  • 3,474
  • 25
  • 23
-2

$app = AppFactory::create();
Add
$app->setBasePath("/project/public/index.php");

TLPtech
  • 1
  • 1