How can I fix my Flask server‘s 405 error that includes OpenAi api?

**题意:**解决包含OpenAI API的Flask服务器中出现的405错误(Method Not Allowed,即方法不允许)

问题背景:

I'm trying to add an API to my webpage and have never used any Flask server before, I have never used Javascript too so this is a completely brand new learning experience. My problem is that I keep receiving a 405 error code saying that the method is not allowed. I keep on using the POST method but it isn't working, I am banking that my issue may be with my HTML code more than my Flask server because the code is extremely generic and simple.

我正在尝试将API添加到我的网页中,但我之前从未使用过任何Flask服务器,也从未使用过JavaScript,所以这对我来说是完全全新的学习体验。我的问题是,我不断收到405错误代码,表示方法不允许。我一直在使用POST方法,但它不起作用。我认为我的问题可能更多地出在我的HTML代码上,而不是Flask服务器,因为我的代码非常通用且简单。

python 复制代码
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)
python 复制代码
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. I'm 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.

我尝试更改代码的结构,卸载并重新安装了Flask。我还广泛使用了chatgpt来尝试编写更好的代码,但它只是让我在原地打转。我希望有人能帮忙解决这个问题。我甚至尝试了一个简单的服务器,它只是输出"hello world",这个是可以工作的,但我真的认为问题可能出在我的JavaScript上。另外,我是个初学者,这应该是我的第一个编程项目之一,所以如果可能的话,请对我宽容一些。谢谢。

问题解决:

You have to add a route for '/' to serve the html file. I also fixed the way you call the OpenAI API because you're using a deprecated one.

你需要添加一个针对'/'的路由来提供HTML文件。我还修复了你调用OpenAI API的方式,因为你正在使用一个已弃用的版本。

python 复制代码
import openai
from flask import Flask, request, jsonify, render_template

chat_client = OpenAI(api_key='....')


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def chat():
    data = request.get_json()
    message = data.get('message')
    
    response = chat_client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": message}
        ],
        max_tokens=50
    )

    return jsonify({'reply': response.choices[0].message.content.strip()})

if __name__ == '__main__':
    app.run(port=5000, debug=True)

sample index.html that I tested with

我测试时使用的示例 index.html 文件

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat app</title>
    <script>
        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 = '';
        }
    </script>
</head>
<body>
    <div id="chat-box"></div>
    <input type="text" id="message" placeholder="Type your message here...">
    <button onclick="sendMessage()">Send</button>
</body>
</html>

Directory structure 目录结构

python 复制代码
- app.py
- templates/
  - index.html
相关推荐
橡晟4 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子4 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
工业甲酰苯胺4 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
Leah01054 小时前
什么是神经网络,常用的神经网络,如何训练一个神经网络
人工智能·深度学习·神经网络·ai
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
Leah01054 小时前
机器学习、深度学习、神经网络之间的关系
深度学习·神经网络·机器学习·ai
企鹅与蟒蛇5 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
autobaba5 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
Rvelamen6 小时前
LLM-SECURITY-PROMPTS大模型提示词攻击测评基准
人工智能·python·安全
【本人】6 小时前
Django基础(一)———创建与启动
后端·python·django