Laravel POST JavaScript 调用 CSRF 未定义

问题描述 投票:0回答:1

我有以下功能:

public function search(Request $request)

{
    return "Hello";
}

路线:

Route::post('/items/search', [ItemController::class, 'search'])->name('items.search');

JS:

try {
    fetch('localhost:8000/items/search', {
        headers: {
            "X-CSRF-TOKEN": {{ csrf_token() }}
        },
        method: 'POST',
        body: "TEST"
    })
    .then(response => response.text())
    .then(data => alert(data));
} catch (error) {
     alert(error);
     alert('Failed to search items.');
}

当我执行 JS 代码时,我收到以下警报错误:

ReferenceError: OvEdMjEpBD3OxCZYVO9pxkKZSdZvdjeDiid9gG65 is not defined

OvEdMjEpBD3OxCZYVO9pxkKZSdZvdjeDiid9gG65 
作为 CSRF 代币,有人可以指出我做错了什么的正确方向吗?

javascript laravel csrf
1个回答
0
投票

看起来它正在尝试找到一个变量,我认为如果你将它包装在“”中,它会按预期工作:

try {
    fetch('localhost:8000/items/search', {
        headers: {
            "X-CSRF-TOKEN": "{{ csrf_token() }}"
        },
        method: 'POST',
        body: "TEST"
    })
    .then(response => response.text())
    .then(data => alert(data));
} catch (error) {
     alert(error);
     alert('Failed to search items.');
}
© www.soinside.com 2019 - 2024. All rights reserved.