I am trying to post data to my Strapi project from a Flutter app. I made sure that the permissions are enabled for unauthenticated users. What is wrong with my request?
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
var reviewObj = jsonEncode({
'review': usrReview,
'rating': usrRating,
});
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
CodePudding user response:
I think this might fix you're problem! I recently ran into this same error a few days ago!
Basically you have to send the body of the POST request as a string.
Here's what it should look like!
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
// Pass the JSON data as a whole string. Then the server should parse it
var reviewObj = '{"review": $usrReview, "rating": $usrRating}';
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
var reviewObj = jsonEncode({
'review': usrReview,
'rating': usrRating,
});
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
Give that a try and let me know if that works!
CodePudding user response:
The problem was that the structure of reviewObj was missing something. I had to include 'data' in it for it to work. Here is what the correct body should look like.
var reviewObj = jsonEncode({
'data': {
'review': usrReview,
'rating': usrRating,
}
});