【问题标题】:Why flutter is unable to send data using POST method to django rest api?为什么颤振无法使用 POST 方法向 django rest api 发送数据?
【发布时间】:2021-07-17 13:42:08
【问题描述】:

这是我在 auth.dart 中的部分代码:

Future<void> signup(String username,String email, String password) async {
      final url =
        'https://ymukeshyadavmrj.pythonanywhere.com/register/';
    try {
      final jb = jsonEncode({
          'username': username,
          'email':email,
          'password':password,
          'password2':password,
      });
      print(jb);
      final response = await http.post(url,body:jb);
      final responseData = json.decode(response.body);
      if (responseData.containsKey('code')) {
        throw HttpException(responseData['message']['message']);
      }
      _token = responseData['access'];
      print("Token =======$_token");
      _refreshToken = responseData['refresh'];

在分配 responseData['access'] 后打印 _token 时返回 null。

注意:我正在为我的项目使用 jwt 身份验证,并且 api 在 Postman 中运行良好。

【问题讨论】:

  • 打印response.body并检查数据。
  • 这很有帮助。此错误正在打印:“详细信息:不支持的媒体类型”文本/纯文本; charset=utf-8" 请求中。"通过在 headers 中添加 content-type 解决。

标签: django flutter django-rest-framework


【解决方案1】:

代码中唯一的错误是我没有在标题中使用内容类型。

【讨论】:

  • 您最终使用了什么内容类型?我尝试添加以下内容,但现在它只是将 POST 转换为 django 端的 OPTIONS { "Content-Type": "application/json", "Accept": "application/json", }
【解决方案2】:

改成这个,应该是URI

final url = Uri.parse('https://ymukeshyadavmrj.pythonanywhere.com/register/');
    

【讨论】:

  • 但如果post 需要一个URI,他将无法运行代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2021-08-11
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多