You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain Flask API报415错误:请求Content-Type非application/json问题排查

问题排查与解决方案

错误核心原因

415 Unsupported Media Type错误的本质是:前端请求未设置application/json的Content-Type,或请求方式与后端API的接收规则不匹配。浏览器直接打开链接发送的是GET请求,而你的API应该期望接收POST类型的JSON格式请求,两者不匹配导致报错。

分端修复方案

1. Python后端API修正

假设你使用FastAPI(LangChain常见搭配),需确保接口配置正确:

  • 明确使用POST方法,通过模型声明JSON请求体结构
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 定义请求体结构
class QARequest(BaseModel):
    url: str
    question: str

@app.post("/qa")  # 必须指定POST方法
def qa_service(request: QARequest):
    # 执行你的LangChain问答逻辑
    answer = your_qa_chain.run({"url": request.url, "question": request.question})
    return {"answer": answer}

如果使用Flask,需启用JSON解析并限定请求方法:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/qa", methods=["POST"])
def qa_service():
    if not request.is_json:
        return jsonify({"error": "Unsupported Media Type"}), 415
    req_data = request.get_json()
    # 执行问答逻辑
    answer = your_qa_chain.run({"url": req_data["url"], "question": req_data["question"]})
    return jsonify({"answer": answer})

2. HTML前端请求修正

前端不能直接通过浏览器打开链接(GET请求)调用API,需通过JavaScript发送符合要求的POST请求:

<!DOCTYPE html>
<html>
<body>
    <input type="text" id="urlInput" placeholder="输入网页链接">
    <input type="text" id="questionInput" placeholder="输入问题">
    <button onclick="submitQuery()">提交</button>
    <div id="result"></div>

    <script>
        async function submitQuery() {
            const url = document.getElementById('urlInput').value;
            const question = document.getElementById('questionInput').value;

            try {
                const res = await fetch('/qa', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json', // 必须设置该头部
                    },
                    body: JSON.stringify({ url, question })
                });
                const data = await res.json();
                document.getElementById('result').textContent = `答案:${data.answer}`;
            } catch (err) {
                console.error('请求失败:', err);
            }
        }
    </script>
</body>
</html>

验证流程

  1. 启动后端API服务
  2. 打开修改后的HTML页面,输入链接和问题后点击提交
  3. 查看浏览器控制台和后端日志,确认请求是否正常接收并返回结果

内容的提问来源于stack exchange,提问作者Swapnil Agnihotri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:42:13