doukeng7426 2016-11-15 10:59
浏览 47

在Laravel 5.3上使用javascript x-editable进行TokenMismatchException

Before marking it as duplicated, i tried the other solutions found on the web, including SO, and none of them solved my issue.

I'm using x-editable plugin to store a new record using a store route.

When the form is submitted, i get a 500 with TokenMismatchException error.

I know about setting the csrf token thing, but i tried it in several ways, and nothing is working.

That's my javascript code:

$.fn.editable.defaults.params = function (params) {
    params._token = window.Laravel.csrfToken;
    return params;
};
$('.editable').each(function () {
    $(this).editable();
});

The html

<head>
    [...]
    <meta name="csrf-token" content="{{ csrf_token() }}">
    [...]
    <script>
        window.Laravel = <?php
        echo json_encode([
            'csrfToken' => csrf_token(),
        ]);
        ?>
    </script>
    [...]
</head>

<button id="note-asl-text"
    data-type="textarea"
    data-placeholder="Aggiungi Nota"
    data-url="{{route('ricettanota.store')}}"
    data-title="Inserisci una nuova nota"
    data-highlight="false"
    data-mode="inline"
    data-send="always"
    data-showbuttons="bottom"
    class="editable"
    >Aggiungi nota</button>

The Route

Route::resource('ricettanota', 'RicettaNotaController');

I already tried all possible combinations of the following:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': window.Laravel.csrfToken
    }
});

$('.editable').each(function () {
    $(this).editable({
        ajaxOptions: {contentType: 'application/json', dataType: 'json'},
        params: function (params) {
            params._token = window.Laravel.csrfToken;
            return JSON.stringify(params);
        }
    });
});

note

$('meta[name="csrf-token"]').attr('content') and window.Laravel.csrfToken are the same

See request screenshot


update

I found out that placing Route::resource('ricettanota', 'RicettaNotaController'); into the api routes file(api.php) causes the issue, while placing the routes into the web routes file (web.php) and using the code above works.

Why using the API i get token mismatch, is still a mystery.

  • 写回答

3条回答 默认 最新

  • dow57588 2016-11-15 11:51
    关注

    try this in your ajaxSetup

    $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据