我創建了處理我的CORS請求中間件:CORS middlware上預檢OPTIONS請求運行,但不能在主請求
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
'Access-Control-Allow-Origin' => '*'
];
$response = $next($request);
foreach ($headers as $key => $value){
$response->headers->set($key, $value);
}
return $response;
}
}
而且我已經把它添加到我的kernel.php
:
'api' => [
'throttle:60,1',
'bindings',
'cors'
],
當我向/user
發送GET
請求時,一切正常,但是當我向/api/answers
發出POST
請求時,出現CORS錯誤:XMLHttpRequest cannot load http://localhost:8000/api/answers. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
。兩者都是在我api.php
:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['middleware' => ['auth:api']], function() {
Route::get('/user', function (Request $request) {
$user = $request->user();
$user->load('locations.company');
$user->load([
'questionlists' => function ($query) {
$query->with('questions.type');
$query->with('difficulty');
}
]);
$amountOfCompletes = count($user->completes);
$user->amountOfCompletes = $amountOfCompletes;
return $user;
});
Route::resource('answers', 'AnswersController');
});
我建議使用此https://github.com/barryvdh/laravel- CORS。爲此節省一些時間。 – ssuhat
我試過了,給了我一個不同的問題:http://stackoverflow.com/questions/40978486/barryvdh-laravel-cors-not-working-for-my-routes?noredirect=1#comment69172987_40978486 – g3mini