Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DNguyen's avatar

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.

0 likes
9 replies
tykus's avatar

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?

DNguyen's avatar

@tykus

AxiosError {message: 'Request failed with status code 405', name: 'AxiosError', 
code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST"
config: {transitional: {…}, adapter: 'xhr', transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message: "Request failed with status code 405"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: {…}, status: 405, statusText: 'Method Not Allowed', headers: AxiosHeaders, config: {…}, …}
stack: "AxiosError: Request failed with status code 405\n    at settle (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=645189f1:1193:12)\n    at XMLHttpRequest.onloadend (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=645189f1:1421:7)"
[[Prototype]]: Error

Here is the error it showed in the console

tykus's avatar

@DNguyen okay, so the Request is being made by axios. Whenever you inspect the Network tab in dev tools, what URL and method do you see as the Request is being made?

tykus's avatar

@DNguyen what is the p segment; do you have a Route group prefix? Can you share the full Routes file?

DNguyen's avatar

@tykus Oh, it kinda self-explained it in the web.php file:

<?php

use App\Http\Controllers\ExploreController;
use App\Http\Controllers\FollowsController;
use App\Http\Controllers\FriendController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PostsController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/



Auth::routes();

Route::post('follow/{user}', [FollowsController::class, 'store']);

Route::view('/search', 'posts.search');

//Home
Route::get('/', [PostsController::class, 'homepage']);
//Create post
Route::get('/p/create', [PostsController::class, 'create']);
//Show post
Route::get('/p/{post}', [PostsController::class, 'show']);
//Store post
Route::post('/p', [PostsController::class, 'store']);
// //Redirect after login
// Route::get('/', [HomeController::class, 'index'])->name('profile.show');
//Show profile
Route::get('/profile/{user}', [App\Http\Controllers\ProfilesController::class, 'index'])->name('profile.show');
//Edit profile
Route::get('/profile/{user}/edit', [App\Http\Controllers\ProfilesController::class, 'edit'])->name('profile.edit');
Route::patch('/profile/{user}', [App\Http\Controllers\ProfilesController::class, 'update'])->name('profile.update');


Route::get('/explore', [ExploreController::class, 'index'])->name('friends.explore');

//Friends
Route::get('/addfriend/{user}', [FriendController::class, 'add']);
Route::get('/cancel/{user}', [FriendController::class, 'cancel']);
Route::get('/accept/{user}', [FriendController::class, 'accept']);
Route::get('/decline/{user}', [FriendController::class, 'decline']);
Route::get('/unfriend/{user}', [FriendController::class, 'unfriend']);

//Comments
Route::post('/comment', [App\Http\Controllers\CommentsController::class, 'saveComm'])->name('comment.save');
Route::delete('/comment/delete/{comment}', [App\Http\Controllers\CommentsController::class, 'deleteComm'])->name('comment.delete');
// Route::get('/comment/load/{postId}', [CommentsController::class, 'loadComments']);

I did add a slash before the URI and the function worked, but I think my mentor will ask me to remove it again lol

tykus's avatar
tykus
Best Answer
Level 104

@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
aniruddhpurohit's avatar

I think you need to pass CSRF token with data in axios.post

axios.post(`comment`, { 
                content: content,
                postId: postId,
				"_token": "{{ csrf_token() }}"
})

Please or to participate in this conversation.