当我使用try和catch来使用API插入操作并且操作插入成功时,但不幸的是toast消息没有打印“注册成功”,它打印的是:
"Error: ClientException: XMLHttpRequest error., uri="http://localhost/dashboard/help_me/signup.php"
Future<void> SignupClient() async {
if (name.text!= "" || phone.text!= "") {
try {
var res = await http.post(
Uri.parse(ApisConnect.signupApi),
body:
{
"name": name.text,
"phone": phone.text,
}
);
var response = jsonDecode(res.body);
if (response["success"] == true) {
Fluttertoast.showToast(msg: 'signed up successfully');
} else if (response["success"] == false) {
Fluttertoast.showToast(msg: 'try again');
}
} catch (e) {
Fluttertoast.showToast(msg: 'Error $e');
}
}
}
我尝试删除 try and catch 或更改它。
您遇到的问题可能是由于 CORS(跨源资源共享)错误造成的。试试这个:
1-将响应正文和标头打印到终端。这将帮助您了解服务器返回的内容以及是否存在必要的 CORS 标头。
2-确保服务器的响应包含必要的 CORS 标头。服务器应通过包含标头来允许来自应用程序来源的请求。您必须在 API Gateway 中启用 CORS,如下所示:
<?php
// Allow from any origin
header("Access-Control-Allow-Origin: *"); //add this line for your flutter app would probably work.
// Allow specific HTTP methods
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
// Allow specific headers
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// Indicate allowed methods and headers
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
exit(0);
...
3-也请查看以下问题:IN Flutter Web getting 'XMLHttpRequest' error while Making HTTP call 以及这个 API Gateway CORS: no 'Access-Control-Allow-Origin' header