Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel POST JavaScript call CSRF is not defined

I have the following function:

public function search(Request $request)

{
    return "Hello";
}

Route:

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

JS:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

When I execute the JS code I get the following alert error:

ReferenceError: OvEdMjEpBD3OxCZYVO9pxkKZSdZvdjeDiid9gG65 is not defined

OvEdMjEpBD3OxCZYVO9pxkKZSdZvdjeDiid9gG65 being the CSRF token, could someone point me in the right direction on what I’m doing wrong?

>Solution :

Looks like it is trying to find a variable, i reckon if you wrap it in "" it will work as expected:

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.');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading