I have created API using PHP and its works as expected and returns result when I run in POSTMAN. But when I tried to call same API in Flutter it didn't work. Below is my Flutter code.
3
-
can you show the error in logs?Gonzalo Gauto– Gonzalo Gauto2020-05-11 23:12:46 +00:00Commented May 11, 2020 at 23:12
-
Are you sure you should be JSON encoding the post data? Check the answer to this question: stackoverflow.com/questions/61741007/… Otherwise, post a screenshot of the working postman request. (The request, not the response.)Richard Heap– Richard Heap2020-05-11 23:37:35 +00:00Commented May 11, 2020 at 23:37
-
I added postman response in question.Abhishek– Abhishek2020-05-12 01:29:20 +00:00Commented May 12, 2020 at 1:29
Add a comment
|
2 Answers
Make sure CORS is enabled in your PHP application. That is likely the cause of this issue. To add CORS support so you can access from any domain add the header to the response: Access-Control-Allow-Origin: *
For restricting by domain and other information about how CORS works I would check this out: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
2 Comments
Abhishek
Thanks for response Brighton, may you guide how to enable CORS in php. I have also uploaded code screen shots and Postman request which works fine...
Brighton Balfrey
@Abhishek Looks like this should work: enable-cors.org/server_php.html or add the header via apache enable-cors.org/server_apache.html
I am able to solve problem, used below code.
static Future<String> addusernew(String firstName, String lastName, String email, String pass) async{
try{
http.Response response = await http.post(url, body: {
"action":_ADD_USER_ACTION,
"firstname":firstName,
"lastname":lastName,
"email":email,
"pass":pass
});
if(response.statusCode == 200){
print("addUser Response 200 : ${response.body}");
return response.body;
}else{
print("addUser Response Error : ${response.body}");
return "Error Adding User";
}
}
catch(e) {
return "Error Adding User : ${e.toString()}";
}
}



