2013-11-22 128 views
1

我試圖通過POST請求創建一個用戶從我的Laravel 4 API從外部站點。我已經添加以下代碼,以我的應用程序/文件filters.php:Laravel 4 API不允許來自外部站點的POST請求

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 

我錯過了什麼嗎?

回答

0

第一個錯誤嚴格是客戶端JavaScript錯誤。錯誤描述的含義正是它所說的。你應該適當地更新你的js。

第二組錯誤消息可能與您爲JavaScript文件發出跨域請求的事實有關,該文件不受PHP發送的頭文件的限制。您需要在網絡服務器上爲此端點配置CORS

+2

謝謝!對於任何其他與Laravel相關的CORS相關問題,我在這裏使用了這個包:https://github.com/barryvdh/laravel-cors來簡化這個過程。 –

相關問題