Im trying to make add an api into my webpage and have never used any Flask server before, I have never used Javascript too so this is a completely brand new learning expirience. My problem is that I keep recieiveing a 405 error code saying that the method is not allowed. I keep on using the POST method but it isnt working, I am banking that my issue maybe with my html code more than my flask server because the code is extremly generic and simple.
import openai
from flask import Flask, request, jsonify
app = Flask(__name__)
openai.api_key = '**my key is in here**'
@app.route('/', methods=['POST'])
def chat():
data = request.get_json()
message = data.get('message')
response = openai.Completion.create(
model="gpt-3.5-turbo",
prompt=message,
max_tokens=50
)
return {'response': response.choices[0].text.strip()}
if __name__ == '__main__':
app.run(port=5000)
async function sendMessage() {
const message = document.getElementById('message').value;
document.getElementById('chat-box').innerHTML += `<div>You: ${message}</div>`;
const response = await fetch('/', {
method: "POST",
body: JSON.stringify({ message }),
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
document.getElementById('chat-box').innerHTML += `<div>Bot: ${data.reply}</div>`;
document.getElementById('message').value = '';
}
I tried changing up the structure of the code, I uninstalled flask and reinstalled it again. I’ve also extensively used chatgpt to try and come up with better code but it just kept taking me in circles. Im hoping someone can help with this.I even tried a simple server that just said hello world which worked, but I truly think the issue might be with my javascript. Also I am a beginner and this is supposed to be one of my first coding projects so please take it easy on me if possible. Thanks.
Overly vile is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.