当我发布帖子请求时,服务器给我以下错误:'XMLHttpRequest无法加载http://localhost/pets2homeback/public/register。在预检响应中,Access-Control-Allow-Headers不允许使用请求头字段X-XSRF-TOKEN。 我跟着你的帖子,我无法在Access-Control-Allow-Headers中允许这个X-XSRF-TOKEN,我真的不明白这个问题,因为路由是一个寄存器,所以没有令牌,我不知道问题出在哪里。
这是我的kernel.php(重点)
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Cors::class,
\App\Http\Middleware\VerifyCsrfToken::class];
这是我的cors.php
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header("Access-Control-Allow-Origin","*")
->header('Access-Control-Allow-Headers', '*')
->header('Allow', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
这是我的routes.php(在Laravel 5.3中是web.php)
header('Access-Control-Allow-Origin','http://localhost');
header('Access-Control-Allow-Credentials', 'true');
Route::get('/', 'IndexController@getIndex');
Route::post('/login', [ 'uses' => 'LoginController@loginAction']);
Route::post('/register', [ 'uses' => 'UserController@register']);
这是我在Angular2中的服务。
register(input){
let params = JSON.stringify(input);
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'});
return this._http.post(this.url+"register", params,{headers: headers})
.map(res => res.json())
}
答案 0 :(得分:4)
我遇到了同样的问题。不是Laravel,而是PHP背景。
为我解决问题的方法是定义这样的标题:
header('Access-Control-Allow-Headers: Content-Type, x-xsrf-token, x_csrftoken');
Angular仅使用XSRF-Token
,但不知何故,我必须定义两者。
希望它有所帮助。