https://zhuanlan.zhihu.com/p/20733964413?utm_psn=1868319333530353664
注意环境变量
打算在服务器上通过Python进行API请求处理,并通过前端接收返回的数据。对于这种场景,通常的做法是通过服务器中转实现,这样前端只与服务器进行交互,服务器再去请求实际的API,从而避免跨域问题。以下是具体的实现细节:
实现步骤
- 在服务器上设置Python中转服务器:
我们将使用Flask框架来搭建一个简单的API中转服务器。 - 前端代码请求中转服务器:
修改前端代码,让它请求我们的中转服务器,而不是直接请求API。
服务器端: 创建中转服务器
首先,安装Flask:
pip install Flask
然后创建一个Python脚本 (如app.py):
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
API_URL = 'http://cloud.nbzch.cn:11434/api/generate'
# 允许跨域请求
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
@app.route('/api/generate', methods=['POST'])
def generate():
data = request.get_json()
try:
response = requests.post(API_URL, json=data, stream=True)
response.raise_for_status()
# 逐块读取响应
response_text = ""
for chunk in response.iter_lines():
if chunk:
chunk_data = json.loads(chunk.decode('utf-8'))
if "response" in chunk_data:
response_text += chunk_data["response"]
return jsonify({"response": response_text})
except requests.exceptions.RequestException as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
前端:修改请求URL指向中转服务器
假设中转服务器运行在 http://localhost:5000
,修改前端JavaScript代码中的API_URL指向中转服务器:
const API_URL = 'http://localhost:5000/api/generate';
document.addEventListener('DOMContentLoaded', (event) => {
function appendMessage(message, isUser = false) {
const container = document.getElementById('chat-container');
const msgDiv = document.createElement('div');
msgDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
msgDiv.textContent = message;
container.appendChild(msgDiv);
container.scrollTop = container.scrollHeight;
}
async function sendMessage() {
const input = document.getElementById('user-input');
const question = input.value.trim();
if (!question) return;
appendMessage(question, true);
input.value = '';
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: "deepseek-r1:32b",
prompt: question,
stream: true
})
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
appendMessage(data.response);
} catch (error) {
appendMessage(`请求出错: ${error.message}`);
}
}
// 回车发送支持
document.getElementById('user-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
});
运行中转服务器
在服务器上运行中转服务器:
python app.py
确保您的前端页面能够访问这个中转服务器的URL,即可以通过 http://localhost:5000/api/generate
进行API请求。
综上
通过这一方案,前端不需要直接与外部API通信,只需和中转服务器通信,从而避免了跨域问题。服务器端的Flask中转服务器将代理前端所有的请求到实际API,再将API的响应返回前端。这样不仅解决了跨域问题,还能增加一层灵活的处理。