如何使用 Laravel API 在 AngularJS 表单中发送 csrf_token()? [英] How to send csrf_token() inside AngularJS form using Laravel API?

查看:35
本文介绍了如何使用 Laravel API 在 AngularJS 表单中发送 csrf_token()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个 angular + laravel rest 应用程序.我可以获得我的数据库的视图.当我尝试添加新项目时.我收到 500 error 告诉我不匹配 csrf 令牌.我的表单布局是:

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);
        });

}

这是我用于我的应用程序的过滤器:

Here is my filter that I use for my application:

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

在我的刀片视图中,我使用它并且它有效:

In my blade views I use this and it works :

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

当我使用 html 表单时如何发送 csrf_token?

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

谢谢

将标头添加到这样的发布请求不会出错.

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' }   
  });

推荐答案

一个选项是将 CSRF 令牌作为常量注入.在您的 head 标签中附加以下内容:

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>

然后在您的模块方法中可以在需要时注入.

Then in your module methods it can be injected when needed.

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

也许你会对这个 示例 Laravel 的源代码感兴趣 +AngularJS 项目.

这篇关于如何使用 Laravel API 在 AngularJS 表单中发送 csrf_token()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆