Laravel - OpenAI API works in local but returns a 404 error on hosting (hPanel)

Hello everyone,

my Laravel project using the openai-php/laravel works great in local but I can’t manage to get a response on the online prod hosted version. Though I uploaded all the project files and everything is exactly the same, the URL, the route and the following code, when I send a POST request it just returns a 404 error.

POST DOMAIN_NAME/api/send 404
fetchAndUpdateHTML @ (index):67
(index):90 Fetch error: Server error.

I don’t know if it’s a route issue, an URL that would need to be redefined for an online use of the API…

The JavaScript :

    //CSRF TOKEN
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.openai.com/v1/chat/completions', true);
    xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);

    //VARIABLES
    const button = document.getElementById('button-submit');
    const chatWindow = document.getElementById('chat-window');
    const url = '{{ url('/api/send') }}';
    const inputField = document.getElementById('input');
    const clean = document.getElementById('button-clean');

    //API FETCH AND HTML UPDATE
    function fetchAndUpdateHTML() {
        const input = document.getElementById('input').value;
        if(isInputValid(input)){
            chatWindow.insertAdjacentHTML('beforeend', `<div class="messages-user">
                            <div class="__user">
                                <p>${input}</p>
                            </div>
                            <img src="{{ asset('/images/avatar.png') }}" alt="Avatar">
                            <div style="clear: both"></div>
                            </div>`);
            inputField.value = '';

            fetch(url, {
                method: 'POST',
                body: JSON.stringify({input: input}),
                headers: {
                    'Content-Type': 'application/json',
                }
            }).then(function (response) {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('Server error.');
                }
            }).then(function (data) {
                chatWindow.insertAdjacentHTML('beforeend', `<div class="messages-bot">
                            <img src="{{ asset('/images/chatbot.png') }}" alt="Avatar">
                            <div class="__bot">
                                <p>${data}</p>
                            </div>
                            </div>
                            `);
            }).catch(function (error) {
                console.log('Fetch error:', error.message);
            });
        }
    }

The web.php :

    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\ChatBotController;

    Route::get(‘/’, function () {
        return view(‘welcome’);
    });

    Route::post(‘send’, [ChatBotController::class, ‘sendChat’]);

The Controller :

public function sendChat(Request $request){
    $result = OpenAI::completions()->create([
        ‘max-token’ => 150,
        ‘model’ => ‘text-davinci-003’,
        ‘prompt’ => $request->input
    ]);

    $response = array_reduce(
        $result->toArray()['choices'],
        fn(string $result, array $choice) => $result . $choice['text'], ""
    );
    
    return $response;
}

Thanks for your time !

The 404 is coming from your own API route, not the call to OpenAI. Make sure your /api/send route exists where you think it does:

php artisan route:list

If you have your project in a subdirectory on hosted, it could differ from your local dev.

Also check any access restrictions on your hosted server, your request to /api/send could be getting blocked.

Thank you for your reply.

I’ve just checked with php artisan route:list and this is what I get :
POST api/send generated::2DreCYHaETnue8f8 › ChatBotController@sendChat

So I guess the route is fine? Yes my project is in a subdirectory on hosted as it is a subdomain, so do you mean I should replace /api/send by the full path? Like ‘subdomain/routes/api/send’ ?

I asked them and there’s apparently no access restriction or problems with an external API call