POST method returns 419 error, and fetch doesn't work (back-end implementation)

Hello everyone,

I am currently trying to use the API in a personal Laravel project ; I don’t really know what is currently wrong in my code, any help would be appreciated.

The JavaScript :

JS
    const xhr = new XMLHttpRequest();
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    xhr.open("GET", "web.php", true);
    xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);

    const button = document.getElementById('button-submit');
    const input = document.getElementById('input').value;
    const chatWindow = document.getElementById('chat-window');
    button.addEventListener('click', function (){
        chatWindow.innerHTML += `<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>`;
        input.value = '';

        fetch('{{ url('send') }}', {
            method: 'POST',
            body: JSON.stringify(input),
            headers: { 'Content-Type': 'application/json' }
        }).then(function(response) {
            if (response.ok) {
                return response.text();
            } else {
                throw new Error('Erreur de réponse du serveur.');
            }
        }).then(function(data) {
            chatWindow.innerHTML += `<div class="messages-bot">
                            <div class="__bot">
                                <p>${data}</p>
                            </div>
                            <img src="{{ asset('/images/chatbot.png') }}" alt="Avatar">
                            </div>
                            `;
        }).catch(function(error) {
            console.log('Erreur lors de la requête fetch:', error.message);
        });
    })

web.php :

Route

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

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

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

The Controller :

Controller

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

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

Thanks

1 Like

Welcome to the forum. Thanks for the code examples and plenty of information.

  1. Is Playground working for you? (This lets us know for certain account is in good standing…) Can also try a simple cURL to the API endpoint to test key and access…

  2. A quick Google search showed possible Laravel issues …

Let us know if account is in good standing and if the 419 might be Laravel specific (not familiar, personally…)

Hope that helps nudge you in the right direction … and that you stick around.

Hello and thank you for the quick reply !!
- Yes the Playground is working for me.
- I’ve just tried replacing the URL of the route with “https://api.openai.com/v1/engines/davinci/completions” and it returns a 401 unauthorized error but it might be linked with something else maybe?
- Also, I didn’t want to use jQuery but I feel like I’ve got lost a bit with all that, especially the CSRF token…

EDIT :
I’ve replaced the fetch function with this :

Fetch

let url = “https://api.openai.com/v1/engines/davinci/completions”;
let bearer = 'Bearer ’ + “MY_OPENAI_KEY
fetch(url, {
method: ‘POST’,
headers: {
‘Authorization’: bearer,
‘Content-Type’: ‘application/json’
},
body: JSON.stringify({
“prompt”: “Once upon a time”,
“max_tokens”: 5,
“temperature”: 1,
“top_p”: 1,
“n”: 1,
“stream”: false,
“logprobs”: null,
“stop”: “\n”
}),

And got a JSON response displayed in my chat

1 Like

That’s an old endpoint, I believe.Please check the docs.

https://platform.openai.com/docs/models/model-endpoint-compatibility

You’ll want to use the new endpoints and send a model parameter…

You are right I’ve replaced it with /v1/completions and model text-davinci-003, thanks.

I’m getting a JSON response, so what could be the issue when I’m not using the cURL ?
I’d like to make the back-end part working…

You might want to check some of the official API libraries and find a better one?

Lots of good ones here…