0

我是 GraphQL 的新手。我需要用 PHP 和 GraphQL 制作一个 API。我遵循了本教程: https ://medium.com/swlh/setting-up-graphql-with-php-9baba3f21501

一切正常,但打开 URL 时,出现此错误:

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

我将此添加到索引页面:

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

但问题没有解决。也许这里缺少一些东西:

return function (App $app) {
    $app->options('/{routes:.*}', function (Request $request, Response $response) {
        // CORS Pre-Flight OPTIONS Request Handler
        return $response;
    });
4

2 回答 2

0

错误消息:不允许的方法
错误状态代码:405

原因
实际上,我们收到此错误是对我们的选项请求而不是对我们的 Post 请求的响应。浏览器在发送 POST、PATCH、PUT、DELETE 等之前发送选项请求。GraphQL 拒绝任何不是 GET 或 POST 的内容,因此选项请求被拒绝

解决方案:转到我们的 cors 中间件并检查其选项是否返回空响应,状态为 200。因此,这样选项请求将永远不会到达 GraphQL 中间件

喜欢 :

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

作为

  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();
    });
于 2020-12-05T13:16:52.690 回答
-1

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

于 2020-08-12T07:31:05.623 回答