首页 > 解决方案 > 选项 405(不允许的方法) slimphp

问题描述

我在共享主机上通过 slim php 制作了 rest api,但前端使用了 angular,所以当我从 localhost 发送数据时出现错误 OPTIONS 405 (Method Not Allowed)。请帮我解决这个问题。

请求方法选项

标签: angularrestcorsslim

解决方案


当您尝试从另一个域调用某些 API 时,会发生此问题。例如,要将请求从“url1.com”发送到“url2.com”,您必须在托管“url2.com”的服务器上设置 CORS 策略。

因此,每个请求都应从您的服务器发送 CORS 标头,例如 Access-Control-Allow-Origin、Access-Control-Allow-Headers、Access-Control-Allow-Methods。

您可以在此处阅读如何执行此操作

此外,您必须为您的请求启用 OPTIONS 请求(只需在每个 OPTION 请求上发送状态代码 200)。这个东西叫做预检请求。您需要为其创建中间件:

$app->add(function (Request $request, Response $response, $next) {
    if ($request->getMethod() !== 'OPTIONS' || php_sapi_name() === 'cli') {
        return $next($request, $response);
    }

    $response = $next($request, $response);

    $response = $response->withHeader('Access-Control-Allow-Origin', '*');
    $response = $response->withHeader('Access-Control-Allow-Methods', '*');
    $response = $response->withHeader('Access-Control-Allow-Headers', '*');    
    return $response;
});

推荐阅读