首页 > 解决方案 > 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.

标签: node.jsnext.js

解决方案


尝试return在调用bcryptand 之前在其最终响应上添加 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." });
        });

推荐阅读