求助:Flutter调用Django后端时出现Unsupported media type请求错误
Hey there! That error message is spelling out exactly what's going wrong—your Django backend doesn't recognize the format of the data you're sending from Flutter. Let's work through this:
Why the error pops up
Django REST Framework expects POST requests with JSON data to include a Content-Type header set to application/json. Right now, your Flutter request isn't specifying this header, so it defaults to text/plain; charset=utf-8—a format Django doesn't know how to process for API endpoints.
The simple fix
All you need to do is add the missing Content-Type header to your http.post call. Here's your updated code:
Future<void> addAlbum(Album album) async { print('5'); final url = Uri.parse('http://127.0.0.1:8000/list-create/'); try { print('6'); final response = await http.post(url, headers: { 'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f', // Add this line to tell Django you're sending JSON 'Content-Type': 'application/json', }, body: json.encode({ 'title': album.title, 'cover': album.cover, // => this is an int 'photos_number': album.photos_number, // => this is an int })); print('6 ed'); final responseData = json.decode(response.body); print(responseData.toString()); final newAlbum = Album( title: album.title, cover: album.cover, photos_number: album.photos_number, ); print('6 edddgg'); _items.add(newAlbum); print('6 f'); notifyListeners(); } catch (error) { print('7'); print(error); throw error; } }
Quick extra checks
- Make sure
album.coverandalbum.photos_numberare actually integers (not strings) before encoding—Django will throw validation errors if the data types don't match your model's expectations. - Double-check that your authorization token is still valid (expired tokens cause separate issues, but it's good to confirm while you're at it).
Once you add that header, your Django backend should correctly parse the JSON data from Flutter, and the error should vanish!
内容的提问来源于stack exchange,提问作者kinda

