Ich habe eine Middleware geschaffen, die meine CORS-Anforderungen verarbeitet:CORS middlware auf Preflight-OPTIONS Anfrage läuft, aber nicht auf Hauptantrag
<?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;
}
}
Und ich habe es hinzugefügt, um meine kernel.php
:
'api' => [
'throttle:60,1',
'bindings',
'cors'
],
Wenn ich eine GET
Anfrage an /user
Anfrage alles funktioniert, aber wenn ich eine POST
Anfrage an /api/answers
Anfrage bekomme ich einen CORS-Fehler: 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.
. Beide sind in meinem 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');
});
mein Vorschlag diese verwenden definiert haben https://github.com/barryvdh/laravel- Kors. Sparen Sie sich etwas Zeit dafür. – ssuhat
Ich versuchte, gab mir ein anderes Problem: http://StackOverflow.com/Questions/40978486/barryvdh-Laravel-Cors-Not-working-for-my-Routes?noredirect=1#comment69172987_40978486 – g3mini