Flask与JS通过POST请求获取JSON数据失败问题求助
Hey there, let's break down the issues you're facing step by step and fix them one by one:
1. The NoneType Error in Flask
Looking at your error log, the core problem here is that server.request.get_json() is returning None, and you're trying to pass that to json.loads()—which expects a string/bytes, not a null value.
First off, get_json() already parses the JSON request body into a Python dictionary—you don't need to run json.loads() on it. That redundant step is what's triggering the error when get_json() returns None.
Why does get_json() return None? Because your frontend isn't sending the request with the correct Content-Type header, or isn't sending valid JSON. Let's fix the frontend first, then adjust the Flask code.
Fixed Flask Code:
from flask import Flask, request # Ensure you're importing request correctly import json import asyncio @app.route("/getData", methods=["POST"]) def getdata(): print("GOT") # Get parsed JSON directly (no need for json.loads) data_rec = request.get_json() # Add a check to handle missing/invalid JSON if not data_rec: return {"error": "No valid JSON received"}, 400 print(data_rec) # Fixed your undefined 'user' print statement try: id = data_rec["id"] # Corrected typo from data_res to data_rec data = asyncio.run(getUser(int(id))) # Use jsonify if your data isn't already JSON-serializable return jsonify(data) if isinstance(data, dict) else data except KeyError: return {"error": "Missing 'id' field in request"}, 400
2. Frontend (JS) Request Mistakes
Your JavaScript has two critical errors that are breaking the request:
- You're using
getResponseHeader(which reads response headers) instead ofsetRequestHeaderto set the content type. - You're sending a raw object instead of converting it to a JSON string.
Fixed JS Code:
const xhr = new XMLHttpRequest(); xhr.open("POST", "https://flask-webapp.co/getData", true); // Tell Flask we're sending JSON xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (this.status >= 200 && this.status < 300) { console.log(this.responseText); let data = JSON.parse(this.responseText); let val = data["val"]; let i = data["i"]; } else { console.error("Request failed with status:", this.status); } }; const params = {"id" : usr_id}; // Convert object to JSON string before sending xhr.send(JSON.stringify(params));
3. CORS Policy Block Error
The browser is blocking your request because your Flask backend doesn't include CORS (Cross-Origin Resource Sharing) headers. To fix this, use the flask-cors extension:
Step 1: Install flask-cors
pip install flask-cors
Step 2: Enable CORS in Your Flask App
from flask import Flask from flask_cors import CORS app = Flask(__name__) # Enable CORS for all routes (restrict to your frontend origin if needed) CORS(app) # If you want to allow only your frontend: # CORS(app, origins=["https://my-site.co"])
Final Notes
After applying these fixes:
- Your frontend will send valid JSON with the correct content type, so Flask can parse it without returning
None. - The redundant
json.loads()call is removed, eliminating theNoneTypeerror. - CORS headers will be added to your Flask responses, resolving the browser's block.
内容的提问来源于stack exchange,提问作者Kushagra

