我正试图通过从外部站点向我的Laravel 4 API发出POST请求来创建一个用户。我已经将以下代码添加到我的app/filters.php文件中:
App::before(function($request)
{
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin', 'http://www.myexternalsite.net');
header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials', 'true');
exit;
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', 'http://www.myexternalsite.net');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Max-Age','86400');
return $response;
});
当我在来自的POST请求上运行我的开发工具时http://www.myexternalsite.net我收到以下警告信息:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead. main-built.js:6
以及以下错误消息:
OPTIONS http://api.mywebsite.com/users 500 (Internal Server Error) main-built.js:7
OPTIONS http://api.mywebsite.com/users No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.myexternalsite.net' is therefore not allowed access. main-built.js:7
我是不是错过了什么?
第一个错误严格来说是客户端javascript错误。错误描述的意思正是它所说的。你应该适当地更新你的js。
第二组错误消息可能与您对javascript文件进行跨域请求有关,该文件不受PHP发送的头的约束。您需要在Web服务器上为此类端点配置CORS