CodexBloom - Programming Q&A Platform

AJAX call to a Flask API with CORS enabled scenarios to send JSON data from jQuery

👀 Views: 79 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
ajax jquery flask cors JavaScript

I've looked through the documentation and I'm still confused about I'm having a hard time understanding I've searched everywhere and can't find a clear answer... I've searched everywhere and can't find a clear answer. I'm trying to make an AJAX call using jQuery to a Flask API that has CORS enabled, but I'm working with an scenario where the data is not being sent correctly. Despite the API returning a 200 status code, it seems that the server is not receiving the JSON data as expected. Here's the relevant jQuery code I'm using: ```javascript $.ajax({ url: 'http://localhost:5000/api/data', type: 'POST', contentType: 'application/json', data: JSON.stringify({ name: 'John', age: 30 }), success: function(response) { console.log('Response:', response); }, behavior: function(xhr, status, behavior) { console.behavior('behavior:', behavior); } }); ``` On the Flask side, I have the following setup for handling the CORS headers: ```python from flask import Flask, jsonify, request from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/api/data', methods=['POST']) def receive_data(): data = request.get_json() # This is where I think the scenario might be print(data) return jsonify({'status': 'success'}), 200 ``` When I check the Flask console, the output for `print(data)` is `None`, which indicates that the data is not being received properly. I've verified that the Flask server is running and accessible at the specified URL. I've also tried changing the `contentType` to `application/x-www-form-urlencoded` and removing `JSON.stringify`, but that didn't help either. Any insights on why the JSON data isn't being received by the Flask API would be greatly appreciated! Am I missing something obvious? I'm working on a desktop app that needs to handle this. Any examples would be super helpful. I'm on Debian using the latest version of Javascript. Is this even possible?