【问题标题】:Post request sends undefined data inn flutter app发布请求在颤振应用程序中发送未定义的数据
【发布时间】:2019-07-25 12:57:50
【问题描述】:

我正在开发一个具有登录功能的简单应用程序,但我无法将用户名和密码正确发送到 nodejs 服务器。我尝试过对其进行编码,将其作为 Map 和 FormData,但似乎没有任何效果。我控制台记录了请求正文并打印“未定义”

我正在使用 Dio dart 包进行 http 请求,并使用 Redux 和 redux thunk 来调度操作。 //我的颤振应用程序上的代码

    ThunkAction<AppState> login(LoginData data) {
          return (Store<AppState> store) async {
            store.dispatch(IsLoading(true));

            try {
              Response response = await Dio().post(
                  "http://10.0.2.2:4000/api/user/login",
                  data: json.encode({"phone": data.phone, "password": data.password}));

              if (response.statusCode == 200) {
                print(json.decode(response.data));
                store.dispatch(IsLoading(false));
              }
            } catch (e) {
              print("Error :(");
            }
          };
        }

// Code on My nodejs 


    router.post("/login", (req, res) => {
    //this log prints undefined
      console.log("Login route: " + req.body.phone);
      var cred = {
        phone: req.body.phone,
        password: req.body.password
      };

      User.findOne({ phone: cred.phone })
        .then(result => {
          if (!result) {
            res.status(400).json({ msg: "no user" });
          } else {
            bcrypt.compare(req.body.password, result.password, (err, isMatch) => {
              if (isMatch) {
                const payload = { id: result._id };
                console.log("Logged in :" + payload);
                jwt.sign(
                  payload,
                  keys.secretOrKey,
                  { expiresIn: 7200 },
                  (err, token) => {
                    res.status(200).json({
                      success: true,
                      token: "Bearer " + token
                    });
                  }
                );
              } else {
                res.status(400).json({ msg: err });
              }
            });
          }
        })
        .catch(err => {
          res.status(400).json({ msg: err });
        });
    });

【问题讨论】:

  • 我遇到了同样的问题,通过在我的请求中添加 HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded 标头解决了
  • 非常感谢它的工作:)
  • @Saman,您可以将其添加为答案而不是评论,因为它解决了发帖者的问题。

标签: node.js dart flutter


【解决方案1】:

要访问服务器端的参数,请将此标头添加到您的请求中:

HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded'

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 2020-09-28
    • 2020-08-12
    • 1970-01-01
    • 2022-01-06
    • 2020-09-24
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多