I am trying to build an angular + laravel rest application. I can get the views of my database. When I try to add new items. I get 500 error telling me mismatch csrf token. My form layout is :

<form class="form-horizontal" ng-submit="addItem()">

  <input type="text" ng-model="itemEntry" placeholder="Type and hit Enter to add item">
</form>

This is how I try to add item to database :

$scope.addItem = function(CSRF_TOKEN) {
    $http.post('/shop', { text: $scope.itemEntry, csrf_token: CSRF_TOKEN} ).success(function(data, status) {
        if(data) {
            var last = _.last($scope.items);
            _token = CSRF_TOKEN;
            $scope.items.push({text: $scope.itemEntry, bought: false, id: (last.id + 1) });
            $scope.itemEntry = '';
            console.log($scope.items);
        } else {
            console.log('There was a problem. Status: ' + status + '; Data: ' + data);
        }
    }).error(function(data, status) {
            console.log('status: ' + status);
        });

}

以下是我在应用程序中使用的过滤:

Route::filter('csrf', function()
{
    if (Session::token() != Input::get('_token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

在我的Blade 视图中,我使用了以下功能:

<input type="hidden" name="_token" value="{{ csrf_token() }}" />

How can I send the csrf_token when I use html forms?

Thanks

Edit 1 : Adding header to post request like this does not give errors.

  $http({
    method  : 'POST',
    url     : '/shop',
    data    :  $scope.itemEntry,  // pass in data as strings
    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }   
  });

推荐答案

An option will be to inject the CSRF token as a constant. Append the following in your head tag:

<script>
  angular.module("app").constant("CSRF_TOKEN", '{{ csrf_token() }}');
</script>

然后在你的模块方法中,它可以在需要时被注入.

app.factory("FooService", function($http, CSRF_TOKEN) {
    console.log(CSRF_TOKEN);
};

Maybe you will be interested of peeking at the source code of this sample Laravel + AngularJS project.

Laravel相关问答推荐

哈希:check()不返回预期结果Laravel 10

LARVAL SAVE 中的关系有

导出所有客户端不起作用,文件保存时没有名称和扩展名

Laravel:如何强制使用 HTTPS?

如何在 Laravel 中显示渲染时间/页面加载时间?

在 VSCode 上调试 Laravel 应用程序

如何更改 Laravel5 中的视图文件夹?

如何使用 Laravel 模型访问数据库视图?

Laravel 5.5 在迁移文件中设置整数字段的大小

控制器中的 Laravel Auth 用户 ID

无法安装 Laravel 包 - 干预图像

PHP 5.5,什么情况下PHP会导致很高的committed memory

Cookie::forget 不工作 laravel 5.1

在 AWS 上找不到 Laravel 5 类Collective\Html\HtmlServiceProvider

Web 服务器如何处理请求?

验证匹配字符串

脚本 php artisan clear-compiled 处理 pre-update-cmd 事件返回错误(Laravel 4.1 升级)

我在哪里放置可以显示 Flash 消息的 Laravel 4 辅助函数?

如何在 Laravel 5.2 中使用 OR 条件将多个参数传递给中间件

Laravel 分页漂亮的 URL