阿贾克斯与Laravel错误与路由 [英] Ajax with Laravel Error with Routing
问题描述
我有laravel路由问题AJAX调用的时候,但我真的不明白,因为我有什么要调用Ajax和成功返回这可能是导致它。任何帮助将大大AP preciated。谢谢!
下面是我的ajax code
$。阿贾克斯({
键入:POST,
网址:baseLocalUrl,// baseLocalUrl =HTTP://本地主机:4567 /管理/使用MenuBuilder / 1 /保存
数据:
{
HTML:$(#comment_area)文本()。
},
成功:功能(数据){
警报(成功!);
}
});
下面是我的路线
路线::组(阵列('preFIX'=>'管理',= GT'前';'权威性'),函数()
{
.....
路线::后(使用MenuBuilder / {}角色/保存,阵列('用途'=>AdminMenuBuilderController @ saveHTML'));
.....
});
下面是我的控制器方法
公共职能saveHTML($ roleId){
// $日codeJson =输入::获得(HTML);
返回成功;
}
这是我得到的错误
POST的http://本地主机:4567 /管理/使用MenuBuilder / 1 /保存500(内部服务器错误)
Laravel日志
production.ERROR:500 - 异常@ /管理/使用MenuBuilder / 1 /保存
在/vagrant/app/filters.php:98异常'照亮\会议\ TokenMismatchException
filters.php
< PHP
/ *
| ------------------------------------------------- -------------------------
|应用与放大器;路由过滤器
| ------------------------------------------------- -------------------------
|
|下面你会发现应用程序事件之前和之后
|可使用的前或一个请求转换后做任何工作中的
|应用。在这里,您也可以注册自定义的路由过滤器。
|
* /
应用::之前(功能($要求)
{
//
});
应用::后(函数($要求,$响应)
{
//
});
/ *
| ------------------------------------------------- -------------------------
|认证过滤器
| ------------------------------------------------- -------------------------
|
|以下过滤器用于验证当前的用户
|会话记录到本申请中。 基本过滤器容易
|集成了快速,简便的检查HTTP基本身份验证。
|
* /
路线::过滤器('权威性',函数()
{
如果(验证::来宾())//如果不记录在用户
{
返回重定向::来宾(用户/登录');
}
});
路线::过滤器(auth.basic',函数()
{
返回验证::基本();
});
/ *
| ------------------------------------------------- -------------------------
|游客的过滤器
| ------------------------------------------------- -------------------------
|
| 客人过滤器的认证过滤器作为相对
|它只是简单地检查未记录在当前用户。一个重定向
|如果是这样,您可以自由改变的响应将发行。
|
* /
路线::过滤器('客人',函数()
{
如果(验证::检查())返回重定向::以(用户/登录/');
});
/ *
| ------------------------------------------------- -------------------------
|角色权限
| ------------------------------------------------- -------------------------
|
|基于角色的访问过滤器。
|
* /
//检查所有的管理路线的作用
委托:: routeNeedsRole(管理*',阵列(管理员),重定向::以('/'));
//检查有关管理操作的权限
委托:: routeNeedsPermission(管理/博客*','manage_blogs,重定向到::('/管理员'));
委托:: routeNeedsPermission(管理/评论*','manage_comments,重定向到::('/管理员'));
委托:: routeNeedsPermission(管理/用户*','manage_users,重定向到::('/管理员'));
委托:: routeNeedsPermission(管理/角色*','manage_roles,重定向到::('/管理员'));
/ *
| ------------------------------------------------- -------------------------
| CSRF保护过滤器
| ------------------------------------------------- -------------------------
|
|该CSRF过滤器是负责保护您的应用程序对
|跨站点请求伪造攻击。如果用户这个特殊的记号
|会议并没有一个在此请求给予配合,我们将保释。
|
* /
路线::过滤器(CSRF',函数()
{
如果(会话::为gettoken()=输入::得到('csrf_token)及!&安培;!会议::为gettoken()=输入::得到('_令牌'))
{
抛出新照亮\会议\ TokenMismatchException;
}
});
/ *
| ------------------------------------------------- -------------------------
|语言
| ------------------------------------------------- -------------------------
|
|检测浏览器的语言。
|
* /
路线::过滤器(detectLang',函数($路线,$请求,$ LANG ='自动')
{
如果($ LANG =自动和放大器;!&安培; in_array($ LANG,配置::得到('app.available_language')))
{
配置::设置('app.locale',$ LANG);
}其他{
$ BROWSER_LANG =!空($ _ SERVER ['HTTP_ACCEPT_LANGUAGE'])?的strtok(用strip_tags($ _ SERVER ['HTTP_ACCEPT_LANGUAGE']),,):'';
$ BROWSER_LANG = SUBSTR($ BROWSER_LANG,0,2);
$ userLang =(in_array($ BROWSER_LANG,配置::得到('app.available_language')))? $ BROWSER_LANG:配置::得到('app.locale');
配置::设置('app.locale',$ userLang);
应用::的setLocale($ userLang);
}
});
您需要在您的AJAX调用的头你的CSRF令牌。试试这个:
在你的HTML < HEAD>
块:
<! - 这是访问您的CSRF令牌比较常见的方法之一。 - >
< META NAME =CSRF令牌CONTENT ={{csrf_token()}}>
和你的AJAX调用:
VAR令牌= $('元[NAME =CSRF令牌])ATTR(内容)。
$阿贾克斯({
键入:POST,
网址:baseLocalUrl,
数据: {
HTML:$(#comment_area)文本()。
},
//添加了CSRF令牌请求头。
标题:{X-CSRF令牌:道理},
成功:功能(数据){
警报(成功!);
}
});
最后,在应用程序/ filters.php
,改变你的CSRF过滤器:
路线::过滤器(CSRF',函数()
{
$令牌=支持::阿贾克斯()?支持::标题(X-CSRF令牌):输入::得到('_令牌');
如果(会话::令牌()!= $令牌)
{
抛出新照亮\会议\ TokenMismatchException;
}
});
I have routing issue with laravel when calling ajax but I don't really understand what could be causing it since what I have should call ajax and return successfully. Any help would be greatly appreciated. Thank you!
Here is my ajax code
$.ajax({
type: "POST",
url: baseLocalUrl, //baseLocalUrl= "http://localhost:4567/admin/menuBuilder/1/save"
data:
{
html: $("#comment_area").text()
},
success: function(data){
alert("success!");
}
});
Here is my route
Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
.....
Route::post('menuBuilder/{role}/save' , array('uses' => 'AdminMenuBuilderController@saveHTML' ));
.....
});
Here is my controller method
public function saveHTML($roleId){
//$decodeJson = Input::get('html');
return "success";
}
This is the error I am getting
POST http://localhost:4567/admin/menuBuilder/1/save 500 (Internal Server Error)
Laravel Log
production.ERROR: 500 - Exception @ /admin/menuBuilder/1/save
exception 'Illuminate\Session\TokenMismatchException' in /vagrant/app/filters.php:98
filters.php
<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
//
});
App::after(function($request, $response)
{
//
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if ( Auth::guest() ) // If the user is not logged in
{
return Redirect::guest('user/login');
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('user/login/');
});
/*
|--------------------------------------------------------------------------
| Role Permissions
|--------------------------------------------------------------------------
|
| Access filters based on roles.
|
*/
// Check for role on all admin routes
Entrust::routeNeedsRole( 'admin*', array('admin'), Redirect::to('/') );
// Check for permissions on admin actions
Entrust::routeNeedsPermission( 'admin/blogs*', 'manage_blogs', Redirect::to('/admin') );
Entrust::routeNeedsPermission( 'admin/comments*', 'manage_comments', Redirect::to('/admin') );
Entrust::routeNeedsPermission( 'admin/users*', 'manage_users', Redirect::to('/admin') );
Entrust::routeNeedsPermission( 'admin/roles*', 'manage_roles', Redirect::to('/admin') );
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
if (Session::getToken() != Input::get('csrf_token') && Session::getToken() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
/*
|--------------------------------------------------------------------------
| Language
|--------------------------------------------------------------------------
|
| Detect the browser language.
|
*/
Route::filter('detectLang', function($route, $request, $lang = 'auto')
{
if($lang != "auto" && in_array($lang , Config::get('app.available_language')))
{
Config::set('app.locale', $lang);
}else{
$browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
$browser_lang = substr($browser_lang, 0,2);
$userLang = (in_array($browser_lang, Config::get('app.available_language'))) ? $browser_lang : Config::get('app.locale');
Config::set('app.locale', $userLang);
App::setLocale($userLang);
}
});
You need to include your CSRF token in the header of your AJAX call. Try this:
In your HTML <head>
block:
<!-- This is one of the more common ways of accessing your CSRF token. -->
<meta name="csrf-token" content="{{ csrf_token() }}">
And for your AJAX call:
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
url: baseLocalUrl,
data: {
html: $("#comment_area").text()
},
// Added the CSRF token to the request header.
header: {"X-CSRF-Token": token},
success: function(data) {
alert("Success!");
}
});
And finally, in app/filters.php
, change your CSRF filter to:
Route::filter('csrf', function()
{
$token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
if (Session::token() != $token)
{
throw new Illuminate\Session\TokenMismatchException;
}
});
这篇关于阿贾克斯与Laravel错误与路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!