skip to Main Content

I’m using Laravel to make a request to an endpoint, which when I test locally works fine and returns what I’m expecting to the frontend, and even when I access the API route/Request URL in the browser it returns the proper response I see in the frontend (ex. http://127.0.0.1:8000/api/makeRequest?user_input=salmon%2Crice returns a perfectly fine response). However, when I open DevTools it tells me I’m getting a 500 Internal Server Error. What’s wrong with my configuration?

api.php:

Route::post('/makeRequest', [AppHttpControllersApiController::class, 'makeRequest'])->name('makeRequest.store');
Route::get('/makeRequest', [AppHttpControllersApiController::class, 'makeRequest'])->name('makeRequest.store');

form in my view:

                <form id="recipeForm" method="post" action="/makeRequest">
                        @csrf
                        <input type="text" id="ingredientInput" placeholder="Ingredient" class="input input-bordered w-full max-w-xs">
                </form>

makeRequest function:

function makeRequest(ingredients) {
    if (ingredients.length > 0) {
        var userInput = ingredients;
        var url = `/api/makeRequest?user_input=${encodeURIComponent(
            userInput
        )}`;
        console.log(ingredients);

        fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            },
            body: JSON.stringify({ ingredients: ingredients }),
        })
            .then((response) => response.text())
            .then((html) => {
                handleApiResponse(html);
            })
            .catch((error) => {
                console.error("Error:", error);
            });
    } else {
        alert("Please add at least one ingredient before submitting.");
    }
}

edit: adding a screenshot from Network tab in DevTools
devtools

2

Answers


  1. You need to add csrf token to your POST request, modify your makeRequest to

    function makeRequest(ingredients) {
        if (ingredients.length > 0) {
            var userInput = ingredients;
            var url = `/api/makeRequest?user_input=${encodeURIComponent(
                userInput
            )}`;
            console.log(ingredients);
    
            fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": $('[name="csrf-token"]').attr('content'),
                    Accept: "application/json",
                },
                body: JSON.stringify({ ingredients: ingredients }),
            })
                .then((response) => response.text())
                .then((html) => {
                    handleApiResponse(html);
                })
                .catch((error) => {
                    console.error("Error:", error);
                });
        } else {
            alert("Please add at least one ingredient before submitting.");
        }
    }
    
    Login or Signup to reply.
  2. the best way to solve this problem if you have the parameters of API or you know where you have to get data you can pass data through the gate request that will help you to solve this problem but before this if you want to return data in Jason so you also need to done view in Jason the problem here you have to define in your route

      <form id="recipeForm" method="post" action="makeRequest.store">
                            @csrf
                            <input type="text" id="ingredientInput" placeholder="Ingredient" class="input input-bordered w-full max-w-xs">
                    </form>
    

    public function store(Request $request)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search