Laravel 4 API不允许来自外部站点的POST请求

时间:2013-11-22 21:20:42

标签: php express laravel-4 cors csrf

我正在尝试通过对来自外部站点的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;
});

当我在http://www.myexternalsite.net的POST请求上运行我的开发工具时,收到以下警告消息:

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

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

第一个错误严重是客户端javascript错误。错误描述完全意味着它所说的内容。你应该适当地更新你的js。

第二组错误消息可能与您正在对javascript文件进行跨域请求这一事实有关,该文件不受PHP发送的标头的限制。您需要在Web服务器上为此类端点配置CORS