OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Laravel 11 Axios POST Request to Controller Method Returns 404 Error

  • Thread starter Thread starter Craig Wang
  • Start date Start date
C

Craig Wang

Guest
I'm facing an issue when trying to execute a POST request from the frontend using Axios to a Laravel controller method. The request URL returns a 404 error as below. AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

My project uses a custom database connection middleware. Below are the detailed configurations and code snippets: web.php

Code:
use App\Http\Controllers\ClientDataController;
use App\Http\Controllers\QueryController;
use App\Http\Controllers\RecordingController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/dashboard', fn() => Inertia::render('Dashboard'))->name('dashboard');

    // Routes that do not need the connection middleware
    Route::get('/clients', [ClientDataController::class, 'index'])->name('client.index');
    Route::get('/clients/create', [ClientDataController::class, 'create'])->name('client.create');
    Route::post('/clients', [ClientDataController::class, 'store'])->name('client.store');
    Route::delete('/clients/{client}', [ClientDataController::class, 'destroy'])->name('clients.destroy');
    Route::post('/set-connection', [ClientDataController::class, 'setConnection'])->name('set-connection');

    // Routes that need the connection middleware
    Route::middleware(['connection'])->group(function () {
        Route::get('/clients/{connection}/queries', [ClientDataController::class, 'show'])->name('clients.show');

        // Queries
        Route::get('/queries', [QueryController::class, 'index'])->name('query.index');
        Route::get('/queries/create', [QueryController::class, 'create'])->name('query.create');
        Route::post('/queries/store', [QueryController::class, 'store'])->name('query.store');
        Route::get('/queries/{id}', [QueryController::class, 'show'])->name('query.show');
        Route::get('/queries/{id}/edit', [QueryController::class, 'edit'])->name('query.edit');
        Route::put('/queries/{id}', [QueryController::class, 'update'])->name('query.update');
        Route::delete('/queries/{id}', [QueryController::class, 'destroy'])->name('query.destroy');
        Route::post('/query/verify', [QueryController::class, 'verify'])->name('query.verify');

        // Recordings
        **Route::post('/recordings/execute/{query}', [RecordingController::class, 'recordQueryExecution'])->name('recording-execution');
    });**
});

I'm so confusing why the error only happens in the '/recordings/execute/{query}'

I think the function 'recordQueryExecution' in the RecordingController is fine because when I executed it with query.store or quey.update. It's work.

RecordingController.php

Code:
namespace App\Http\Controllers;

use App\Models\Query;
use App\Models\Recording;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class RecordingController extends Controller
{
    public function recordQueryExecution(Query $query)
    {
        try {
            $result = DB::select($query->query_sql);
            $csvFilePath = $this->generateCsvFile($query->id, $result);

            $recording = new Recording();
            $recording->query_id = $query->id;
            $recording->query_sql = $query->query_sql;
            $recording->csv_file_path = $csvFilePath;
            $recording->updated_by = Auth::id();
            $recording->updated_at = now();
            $recording->status = 'success';
            $recording->save();

            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            $recording = new Recording();
            $recording->query_id = $query->id;
            $recording->query_sql = $query->query_sql;
            $recording->updated_by = Auth::id();
            $recording->updated_at = now();
            $recording->status = 'fail';
            $recording->fail_reason = $e->getMessage();
            $recording->save();

            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    private function generateCsvFile($queryId, $result)
    {
        $csvDir = storage_path("app/public/csv");

        if (!file_exists($csvDir)) {
            mkdir($csvDir, 0777, true);
        }

        $csvFileName = "query_{$queryId}_" . now()->format('Ymd_His') . '.csv';
        $csvFilePath = "{$csvDir}/{$csvFileName}";

        $file = fopen($csvFilePath, 'w');

        if (!empty($result)) {
            fputcsv($file, array_keys((array)$result[0]));
        }

        foreach ($result as $row) {
            fputcsv($file, (array)$row);
        }

        fclose($file);

        return $csvFileName;
    }
}

Axios Request in Show.jsx:

Code:
import axios from 'axios';

const runQuery = async (queryId) => {
        try {
            const response = await axios.post(`/recordings/execute/${queryId}`);
            if (response.data.success) {
                window.location.reload();
            } else {
                console.error("Error running query:", response.data.message);
            }
        } catch (error) {
            console.error("Error running query:", error);
        }
    };

I'm not sure but maybe it's the reason I used the wrong way to register the middleware.

bootstrap/app.php

Code:
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
            \App\Http\Middleware\Connection::class,
        ]);

        $middleware->alias([
            'connection' => \App\Http\Middleware\Connection::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Models/Query.php

Code:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Query extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'query_sql', 'created_by', 'updated_by'];

    public function setConnectionByClient($client)
    {
        $this->setConnection($client);
        return $this;
    }

    public function execute()
    {
        return DB::connection($this->getConnectionName())->select($this->query_sql);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function outputtings()
    {
        return $this->hasMany(Outputting::class);
    }

    public function recordings()
    {
        return $this->hasMany(Recording::class);
    }

    public function schedules()
    {
        return $this->hasMany(Schedule::class);
    }
}

Are there any obvious issues with my routes or controller methods that might be causing this 404 error?

Tried 1.Verified the routes in web.php are correctly set. 2.Confirmed that the recordQueryExecution method works when called directly from QueryController.

<p>I'm facing an issue when trying to execute a POST request from the frontend using Axios to a Laravel controller method. The request URL returns a 404 error as below.
<strong>AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}</strong></p>
<p>My project uses a custom database connection middleware. Below are the detailed configurations and code snippets:
<strong>web.php</strong></p>
<pre><code>use App\Http\Controllers\ClientDataController;
use App\Http\Controllers\QueryController;
use App\Http\Controllers\RecordingController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/dashboard', fn() => Inertia::render('Dashboard'))->name('dashboard');

// Routes that do not need the connection middleware
Route::get('/clients', [ClientDataController::class, 'index'])->name('client.index');
Route::get('/clients/create', [ClientDataController::class, 'create'])->name('client.create');
Route::post('/clients', [ClientDataController::class, 'store'])->name('client.store');
Route::delete('/clients/{client}', [ClientDataController::class, 'destroy'])->name('clients.destroy');
Route::post('/set-connection', [ClientDataController::class, 'setConnection'])->name('set-connection');

// Routes that need the connection middleware
Route::middleware(['connection'])->group(function () {
Route::get('/clients/{connection}/queries', [ClientDataController::class, 'show'])->name('clients.show');

// Queries
Route::get('/queries', [QueryController::class, 'index'])->name('query.index');
Route::get('/queries/create', [QueryController::class, 'create'])->name('query.create');
Route::post('/queries/store', [QueryController::class, 'store'])->name('query.store');
Route::get('/queries/{id}', [QueryController::class, 'show'])->name('query.show');
Route::get('/queries/{id}/edit', [QueryController::class, 'edit'])->name('query.edit');
Route::put('/queries/{id}', [QueryController::class, 'update'])->name('query.update');
Route::delete('/queries/{id}', [QueryController::class, 'destroy'])->name('query.destroy');
Route::post('/query/verify', [QueryController::class, 'verify'])->name('query.verify');

// Recordings
**Route::post('/recordings/execute/{query}', [RecordingController::class, 'recordQueryExecution'])->name('recording-execution');
});**
});

</code></pre>
<p>I'm so confusing why the error only happens in the '/recordings/execute/{query}'</p>
<p>I think the function 'recordQueryExecution' in the RecordingController is fine because when I executed it with query.store or quey.update. It's work.</p>
<p><strong>RecordingController.php</strong></p>
<pre><code>namespace App\Http\Controllers;

use App\Models\Query;
use App\Models\Recording;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class RecordingController extends Controller
{
public function recordQueryExecution(Query $query)
{
try {
$result = DB::select($query->query_sql);
$csvFilePath = $this->generateCsvFile($query->id, $result);

$recording = new Recording();
$recording->query_id = $query->id;
$recording->query_sql = $query->query_sql;
$recording->csv_file_path = $csvFilePath;
$recording->updated_by = Auth::id();
$recording->updated_at = now();
$recording->status = 'success';
$recording->save();

return response()->json(['success' => true]);
} catch (\Exception $e) {
$recording = new Recording();
$recording->query_id = $query->id;
$recording->query_sql = $query->query_sql;
$recording->updated_by = Auth::id();
$recording->updated_at = now();
$recording->status = 'fail';
$recording->fail_reason = $e->getMessage();
$recording->save();

return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
}
}

private function generateCsvFile($queryId, $result)
{
$csvDir = storage_path("app/public/csv");

if (!file_exists($csvDir)) {
mkdir($csvDir, 0777, true);
}

$csvFileName = "query_{$queryId}_" . now()->format('Ymd_His') . '.csv';
$csvFilePath = "{$csvDir}/{$csvFileName}";

$file = fopen($csvFilePath, 'w');

if (!empty($result)) {
fputcsv($file, array_keys((array)$result[0]));
}

foreach ($result as $row) {
fputcsv($file, (array)$row);
}

fclose($file);

return $csvFileName;
}
}

</code></pre>
<p><strong>Axios Request in Show.jsx:</strong></p>
<pre><code>import axios from 'axios';

const runQuery = async (queryId) => {
try {
const response = await axios.post(`/recordings/execute/${queryId}`);
if (response.data.success) {
window.location.reload();
} else {
console.error("Error running query:", response.data.message);
}
} catch (error) {
console.error("Error running query:", error);
}
};

</code></pre>
<p>I'm not sure but maybe it's the reason I used the wrong way to register the middleware.</p>
<p><strong>bootstrap/app.php</strong></p>
<pre><code><?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
\App\Http\Middleware\Connection::class,
]);

$middleware->alias([
'connection' => \App\Http\Middleware\Connection::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
</code></pre>
<p><strong>Models/Query.php</strong></p>
<pre><code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Query extends Model
{
use HasFactory;

protected $fillable = ['name', 'query_sql', 'created_by', 'updated_by'];

public function setConnectionByClient($client)
{
$this->setConnection($client);
return $this;
}

public function execute()
{
return DB::connection($this->getConnectionName())->select($this->query_sql);
}

public function creator()
{
return $this->belongsTo(User::class, 'created_by');
}

public function updater()
{
return $this->belongsTo(User::class, 'updated_by');
}

public function outputtings()
{
return $this->hasMany(Outputting::class);
}

public function recordings()
{
return $this->hasMany(Recording::class);
}

public function schedules()
{
return $this->hasMany(Schedule::class);
}
}
</code></pre>
<p>Are there any obvious issues with my routes or controller methods that might be causing this 404 error?</p>
<p>Tried
1.Verified the routes in web.php are correctly set.
2.Confirmed that the recordQueryExecution method works when called directly from QueryController.</p>
 

Online statistics

Members online
0
Guests online
3
Total visitors
3
Top