You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter+Dio调用登录API遇HTTP 400及data空指针问题求助

Flutter登录请求HTTP 400错误排查与解决

核心问题定位

你的auth_services.dart中,POST请求的data字段使用了不必要的转义双引号,导致发送的请求体不是合法的JSON对象,后端无法解析到有效参数,因此返回400错误并提示data为null。

修复代码

修改auth_services.dart中的login方法,去掉data里的转义双引号,直接传递Map对象:

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:frontend/services/api_services.dart';

class AuthServicess {
  Dio dio = Dio(BaseOptions(connectTimeout: Duration(seconds: 5)));
  login(email, password) async {
    try {
      return await dio.post(
        'http://localhost:3000/users/login',
        // 去掉转义双引号,直接传递Map
        data: {"email": email, "password": password},
      );
    } on DioException catch (e) {
      print(e.toString());
      Fluttertoast.showToast(msg: e.toString());
    }
  }
}

额外检查点

  • 确认username和password对应的TextField已正确绑定TextEditingController实例,比如:
    final username = TextEditingController();
    final password = TextEditingController();
    
    // 在TextField中绑定
    TextField(controller: username, ...)
    TextField(controller: password, ...)
    
  • 检查NestJS后端的登录接口DTO配置,确保email和password字段的校验规则正确,比如:
    // 示例DTO
    export class LoginDto {
      @IsEmail()
      email: string;
    
      @IsString()
      @MinLength(6)
      password: string;
    }
    
  • 可以给Dio添加请求拦截器,打印完整请求信息,确认参数是否正确发送:
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print('请求参数: ${options.data}');
        print('请求头: ${options.headers}');
        return handler.next(options);
      },
    ));
    

内容的提问来源于stack exchange,提问作者anlele1701

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:57:30