“错误”:“415 不支持的媒体类型:未尝试加载 JSON 数据,因为请求内容类型不是“application/json”。”

问题描述 投票:0回答:1

我正在开发一个 React-Python(Flask) 项目。我在后端不断收到错误:

'415 不支持的媒体类型:未尝试加载 JSON 数据,因为请求内容类型不是“application/json”。

在前端:

'student-register.tsx:93 错误:语法错误:JSON 输入意外结束'

我不知道问题出在后端还是前端。我重新检查了我的 React 端点,但没有看到问题出在哪里:

export const StudentRegister = () => {
  const [form] = Form.useForm();

  const onFinish = async (values: any) => {
    try {
      const formData = new FormData()
      
      if (values.image && values.image.length > 0) {
        formData.append('image', values.image[0].originFileObj);
        console.log(formData)
      }  
      
      const imageResponse = await fetch('/facial-data', {
        method: 'POST',
        body: formData
      })

      const imageResult = await imageResponse.json();
      console.log('Image upload response:', imageResult);

      delete values.image;

      const formResponse = await fetch('http://localhost:5000/student', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const data = await formResponse.json();

      if (formResponse.ok) {
        message.success(data.message);
        form.resetFields();
        
      } else {
        message.error(data.error);
      }
    } catch (error) {
      console.error('Error:', error);
    }

    window.location.href = '/login';
  };

  return ()

我的烧瓶端点看起来也可以:

@app.route('/student', methods=['GET','POST'])
def register():
    print(request.headers)
    print("---------")
    print(request.data)
    session = Session()

    try:
        data = request.json
        user = User(
            first_name=data.get('firstname'),
            last_name=data.get('lastname'),
            email=data.get('email'),
            reg_no=data.get('reg_no'),
            role=data.get('role'),
            password=data.get('password')
        )
        user.save_to_db(session)

        response = {'message': 'Registration successful'}
        return jsonify(response), 200
    except Exception as e:
        session.rollback()
        return jsonify({'error': str(e)}), 500
    finally:
        session.close()

可能是什么问题?任何帮助将不胜感激。

我尝试打印标题并得到:

Host: localhost:5000
Connection: keep-alive
Cache-Control: max-age=0
Sec-Ch-Ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-US,en;q=0.9
Cookie: Pycharm-119ea720=95741790-f49e-4011-8331-67c2c03dcc92; _ga=GA1.1.1648027930.1713378416; _ga_ZLVG7NETWG=GS1.1.1713532635.4.1.1713533069.0.0.0; _ga_1M7M0TRFHS=GS1.1.1713532635.4.1.1713533069.0.0.0; _ga_K62YRZRY27=GS1.1.1713532635.4.1.1713533069.0.0.0


---------
b''

看起来请求标头是正确的,并且请求正文(request.data)为空(b'')。

我也尝试过

console.log(JSON.stringify(values))
并且表单值已正确输入到
onfinish
函数中。

javascript python reactjs flask
1个回答
0
投票

打印请求头时,没有获取Content-type键中的application/json值。确保将其发布在请求标头中。

© www.soinside.com 2019 - 2024. All rights reserved.