Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23218

"error": "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'."

$
0
0

I am working on a React-Python(Flask) project. I keep getting the error in the backend:

'415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'.

and on the frontend:

'student-register.tsx:93 Error: SyntaxError: Unexpected end of JSON input'

I don't know whether the issue is with the backend side or the frontend side. I have rechecked my React endpoint and I don't see where the problem:

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 ()

And my flask endpoint also looks okay to:

@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()

What could be the issue? Any help will be appreciated.

I tried to print the header and got:

Host: localhost:5000Connection: keep-aliveCache-Control: max-age=0Sec-Ch-Ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"Sec-Ch-Ua-Mobile: ?0Sec-Ch-Ua-Platform: "Windows"Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36Accept: 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.7Sec-Fetch-Site: noneSec-Fetch-Mode: navigateSec-Fetch-User: ?1Sec-Fetch-Dest: documentAccept-Encoding: gzip, deflate, br, zstdAccept-Language: en-US,en;q=0.9Cookie: 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''

looks like the request headers are correct, and the request body (request.data) is empty (b'').

I also tried to console.log(JSON.stringify(values)) and the form values are being fed correctly into the onfinish function.


Viewing all articles
Browse latest Browse all 23218

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>