I would guess that the default action (of the form being submitted) is not being prevented and you are POSTing instead to the current URL. Can you share the full error message?
Axios 405 Method is not allowed on POST route
I'm using Axios for posting comments, here is the code:
document.addEventListener('DOMContentLoaded', function () {
const contentInput = document.getElementById('content');
contentInput.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
saveComment();
loadComments();
}
});
function saveComment() {
const content = contentInput.value.trim();
const postId = document.querySelector('input[name="postId"]').value;
if (content) {
axios.post(`comment`, { // Use the correct route name here
content: content,
postId: postId
})
.then(function (response) {
// Handle success, e.g., update the UI
console.log(response.data);
contentInput.value = ''; // Clear the input field
})
.catch(function (error) {
// Handle error, e.g., display an error message
console.log(error);
});
}
}
});
The route I'm using:
Route::post('comment', [App\Http\Controllers\CommentsController::class, 'saveComm'])->name('comment.save');
The content and post ID is get through the inputs in this form:
<form method="POST" autocomplete="off">
@csrf
<input id="content" type="text" class="comment"
placeholder="Say something..." name="content" autofocus>
<input type="hidden" name="postId" value="{{ $post->id }}">
</form>
Is there anything wrong with these? I tried changing the route to /comment/{post} in web.php and /comment/${postId} in the JavaScript code. It worked but my mentor told me to revert the routes back and now the function isn't working.
@DNguyen there's your problem...
The URL( http://localhost:8000/p/comment) for the Request does not match the URL you intended (http://localhost:8000/comment) based on the Route definition:
Route::post('/comment', [App\Http\Controllers\CommentsController::class, 'saveComm'])->name('comment.save');
Instead it matches Route::get('/p/{post}', [PostsController::class, 'show']); . This is because it is relative to your current URL.
The easiest solution is to make the URL absolute
axios.post(`/comment`, { // Use the correct route name here
Please or to participate in this conversation.