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.");
}
}
2
Answers
You need to add csrf token to your POST request, modify your
makeRequest
tothe 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
public function store(Request $request)