【发布时间】:2017-04-20 22:02:40
【问题描述】:
我创建了一个处理我的 CORS 请求的中间件:
<?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');
});
【问题讨论】:
-
我的建议是使用这个github.com/barryvdh/laravel-cors。为您节省一些时间。
-
我试过了,给了我一个不同的问题:stackoverflow.com/questions/40978486/…
标签: php laravel api http-headers middleware