应用程序中的 API 内部错误 500,在服务器中工作正常

问题描述 投票:0回答:1

当我在服务器中尝试 API 时,我工作正常并且响应也出现,但是当我在 Flutter 应用程序中调用该 post API 时,它会显示 500 内部服务器错误。 我的代码有什么问题吗?

我的API代码:

Future<void> postData(Cart cart, Address selectedAddress) async {
  final url = 'https://api.vezigo.in/v1/orders';

  final body = {
    "items": cart.items.map((cartItem) {
      return {
        "pack": {
          "price": cartItem.price.toString(),
          "unit": cartItem.package,  
          "quantity": cartItem.quantity.toString(),
        },
        "product": cartItem.name,
        "quantity": cartItem.quantity
      };
    }).toList(),
    "billAmount": cart.totalAmount.toStringAsFixed(2),
    "userDetails": {
      "name": selectedAddress.yourName,
      "phoneNumber": selectedAddress.phoneNumber,
      "altPhoneNumber": selectedAddress.alternatePhoneNumber ,
      "address": "${selectedAddress.houseNumber}, ${selectedAddress.landmark}",
      "notes": selectedAddress.notes 
    },
    "geo": {
      "lat": selectedAddress.latitude.toString(),
      "lng": selectedAddress.longitude.toString()
    }
  };

  final prefs = await SharedPreferences.getInstance();
  final accessToken = prefs.getString('accessToken');

  try {
    print('Request body: ${json.encode(body)}');
    print('Authorization: Bearer $accessToken');

    final response = await http.post(
      Uri.parse(url),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $accessToken',
      },
      body: json.encode(body),
    );

    if (response.statusCode == 200) {
      print('Response data: ${response.body}');
      _showOrderSuccessfulPopup(context);
    } else {
      // Log response for debugging
      print('Error: ${response.statusCode}');
      print('Response body: ${response.body}');
    }
  } catch (e) {
    print('Exception: $e');
  }
}

 
  void _showOrderSuccessfulPopup(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Image.asset('assets/payment/tick.png'),
          content: const Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                'Order Successful',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                  fontSize: 30,
                ),
              ),
              SizedBox(height: 10),
              Text(
                'Your order #986547676 has been placed successfully!',
                textAlign: TextAlign.center,
              ),
            ],
          ),
          actions: [
            Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.appbarColor,
                        padding: const EdgeInsets.symmetric(
                            horizontal: 50, vertical: 15)),
                    onPressed: () {},
                    child: const Text('Track my Order',
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.w800)),
                  ),
                  const SizedBox(height: 18),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        side: const BorderSide(
                            color:AppColors.appbarColor, width: 1),
                        padding: const EdgeInsets.symmetric(
                            horizontal: 70, vertical: 15)),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: const Text('Go Back',
                        style: TextStyle(
                            color: AppColors.appbarColor,
                            fontWeight: FontWeight.w800)),
                  ),
                  const SizedBox(height: 20)
                ],
              ),
            ),
          ],
        );
      },
    );
  }

以及我来自 API 的打印声明:

flutter: 请求正文: {"items":[{"pack":{"price":"36.0","unit":{"_id":"66d03fcc0273b734500c9eaf","quantity":1,"unit":"公斤","价格":36},"数量":"1"},"产品":"Aalu","数量":1},{"包装":{"价格":"100.0","单位":{"_id":"66d0400e0273b734500c9eb7","数量":2,"单位":"公斤","价格":100},"数量":"1"},"产品":"Pyaaz","数量":1},{"包装":{"价格":"470.0","单位":{"_id":"66d041cc0273b734500c9ec6","数量":3,"单位":"公斤","价格" :470},"数量":"1"},"产品":"傻瓜哥比","数量":1},{"包":{"价格":"1600.0","单位":{"_id ":"66d045240273b734500c9ed4","数量":5,"单位":"公斤","价格":1600},"数量":"1"},"产品":"西兰花","数量":1} ],"billAmount":"2206.00","userDetails":{"name":"TAnu","phoneNumber":"9602046633","altPhoneNumber":"9602046633","address":"巴斯尼,巴斯尼","笔记":"你好"},"geo":{"lat":"26.21638011850468","lng":"73.01504015922548"}} 颤动:授权:承载eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NmVkMmRhMjliZGZlMTAwNmUzOTY5YWQiLCJpYXQiOjE3MjY4MTk3NzEsImV4cCI6MTcyNjgyMTU3MSwidHlwZ SI6ImFjY2VzcyJ9.3Pg_GNqOv4jvdgl62xSX1ljlJSnCafs1HWEvtkEunv0 颤振:错误:500 flutter: 响应正文: {"code":500,"message":"内部服务器错误","data":{}}

flutter dart postman
1个回答
0
投票

这里有一些建议:

  • 正确检查标题
  • 正确检查访问令牌。确保令牌未过期。
  • 再次检查请求正文。使用 ChatGPT 进行交叉检查。

如果这仍然不起作用,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.