node.js - Next.js 的 API 路由不发送响应
问题描述
Next.js 在请求我的 API 路由时发送此错误:
API resolved without sending a response for /api/login, this may result in stalled requests.
我猜 API 路由的内容是有效的。大多数边缘情况都已解决。我还要补充一点,成功登录时发生了错误。
export default withSession(async (req, res) => {
if (req.method !== "POST") {
return res.status(405).send({ error: "Tylko metoda POST jest dozwolona." });
}
const { username, password } = req.body;
if (!username || !password) {
return res.status(401).send({ error: "Nazwa użytkownika i hasło nie mogą być puste." });
}
try {
const knex = getKnex();
const user = await knex<User>("users").select("*").where("username", username).first();
if (!user) {
return res.status(401).send({ error: "Użytkownik o takiej nazwie nie istnieje." });
}
bcrypt.compare(password, user.password, async function (error) {
if (error) {
return res.status(403).send({ error: "Podane hasło jest nieprawidłowe." });
}
const { password, ...result } = user;
req.session.set("user", result);
await req.session.save();
res.status(200).send({ message: "Zostałeś zalogowany." });
});
} catch (error) {
res.status(error?.status || 500).send({ error: error.message });
console.error(error.stack);
}
});
该withSession
函数是用于处理next-iron-session
.
解决方案
尝试return
在调用bcrypt
and 之前在其最终响应上添加 a,例如:
return bcrypt.compare(password, user.password, async function (error) {
if (error) {
return res.status(403).send({ error: "Podane hasło jest nieprawidłowe." });
}
const { password, ...result } = user;
req.session.set("user", result);
await req.session.save();
return res.status(200).send({ message: "Zostałeś zalogowany." });
});
推荐阅读
- json - 邮递员从环境变量在 Json 文件中添加数组
- https - 用于负载平衡 gRPC 流量的 HTTPS 证书
- c# - 如何在 C# 的并行任务中通过 tcp 套接字接收数据?
- symfony - 如何通过 JsFormValidatorBundle 验证的表单的 ajax 部分进行更改
- angular - 如何使用 angular 2 在prime ng中一次显示一个日历
- javascript - 在服务器上发布后,asp.net mvc ajax 调用不调用控制器
- java - JLS、JSR 和 JEP 之间有什么区别(或关系)?
- c# - 如何更改 Unity Text 中的文本
- mongodb - 如何根据MongoDB中where条件中引用的文档详细信息获取父文档详细信息?
- qemu - qemu-system-aarch64 从来宾系统内退出