【发布时间】:2019-03-25 02:11:53
【问题描述】:
我在共享主机上通过 slim php 制作了 rest api,但前端使用 angular,所以当我从 localhost 发送数据时出现错误 OPTIONS 405 (Method Not Allowed)。请帮我解决这个问题。
【问题讨论】:
我在共享主机上通过 slim php 制作了 rest api,但前端使用 angular,所以当我从 localhost 发送数据时出现错误 OPTIONS 405 (Method Not Allowed)。请帮我解决这个问题。
【问题讨论】:
当您尝试从另一个域调用某些 API 时会发生此问题。例如,要将请求从“url1.com”发送到“url2.com”,您必须在托管“url2.com”的服务器上设置 CORS 策略。
因此,每个请求都应从您的服务器发送 CORS 标头,例如 Access-Control-Allow-Origin、Access-Control-Allow-Headers、Access-Control-Allow-Methods。
你可以阅读如何做到这一点here
此外,您必须为您的请求启用 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;
});
【讨论】:
我已经读过这个。但我不明白配置。我将配置此代码。是吗?
<?php
使用 \Psr\Http\Message\ServerRequestInterface 作为请求; 使用 \Psr\Http\Message\ResponseInterface 作为响应;
$app = 新 \Slim\App;
$app->post('/login', function (Request $request, Response $response, array $args) {
$email = $request->getParam('email_login');
$response->getBody()->write("Hello, $email");
return $response;
});
【讨论】: