【发布时间】: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,您可以将其添加为答案而不是评论,因为它解决了发帖者的问题。