I am creating a simple app, using a Flask API and Flutter/Dart frontend.
To get all the expenses I make a GET request providing a User_ID in the body. This works when running the application in the IOS emulator, but it doesn't work when I run it on Chrome.
The simplified code is as follows;
class ExpenseApi {
// works on simulator, but not on web..?
static Future<List<Expense>> getExpense(int id) async {
final url = Uri.parse(Config.apiEndpoint + '/api/get_all_expenses');
Map<String, String> requestBody = <String, String>{
'user_id': id.toString(),
};
// It seems the problem is in the following line
var request = http.MultipartRequest('GET', url)..fields.addAll(requestBody);
var response = await request.send();
final respStr = await response.stream.bytesToString();
var data = jsonDecode(respStr);
List _temp = [];
for (var i in data) {
_temp.add(i);
}
return Expense.expensesFromSnapshot(_temp);
}
}
it is called like this:
Future<void> getExpensesAndBudgets() async {
tempExpenses = await ExpenseApi.getExpense(1);
}
late List<Expense> tempExpenses = [];
getExpensesAndBudgets();
FLASK API code:
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
db = DBConnection()
@app.route("/api/get_all_expenses", methods=['GET', 'OPTIONS'])
def get_all_expenses():
print("Call coming in!")
if request.method == 'GET':
print("Type: ", request.headers.get('Content-Type'))
id = request.form.get('user_id')
print(id)
result = jsonify(db.get_all_expenses(id))
return result
DB class:
def get_all_expenses(self, id):
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
query = '''
SELECT expenses.name, expenses.amount, budgets.name as budget_name FROM expenses LEFT JOIN budgets ON expenses.budget_id=budgets.id WHERE expenses.user_id=?
'''
try:
result = []
c.execute(query, [id])
conn.commit()
columns = [desc[0] for desc in c.description]
rows = c.fetchall()
for row in rows:
row = dict(zip(columns, row))
result.append(row)
print(result)
return result
except sqlite3.Error:
print('SQLite error!')
return []
The second print statement will return 'None' when calling the request from the browser-based app, but in Postman and in the Emulator based version it will print '1'. Note that these statements are just for debugging.
The final result of the call when trying from the browser is '[]', while in Postman and in the emulator it returns the data requested.
Does anyone know how to send the user_id from the browser-based app? Or will I need to rethink my design?