这是我使用 NextJS 和
server actions
的第一个请求,我正在使用 NextResponse
将响应从服务器发送回客户端组件,但它不起作用,因为我收到错误 Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported
:
db.js
import mysql from "mysql2/promise";
let connection;
export const createConnection = async () => {
if (!connection) {
connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
});
}
return connection;
};
actions.js
"use server";
import { createConnection } from "@/db";
import { NextResponse } from "next/server";
export async function login(data) {
const { email, password } = data;
try {
const db = await createConnection();
const [user] = await db.query(
"SELECT id,firstName,lastName, image,DATE_FORMAT(birth_date, '%Y-%m-%d') as birthDate,gender, position, email, role, password,status FROM `users` WHERE email = ? AND status = 'approved'",
[email]
);
if (user.length == 0) {
return NextResponse.json({ message: "Invalid credentials." }, { status: 400 });
}
console.log(user);
return NextResponse.json(user);
} catch (error) {
return NextResponse.json({ error: error.message });
}
}
我发现错误是由这一行引起的:
return NextResponse.json({ message: "Invalid credentials." }, { status: 400 });
这可能意味着查询执行是错误的,但正如你所看到的,我仍然返回一个对象,但它不返回响应,而是返回错误,即使我将其更改为这样的:
return "empty user";
它仍然没有返回任何内容(空响应)
page.js
"use client";
import { useForm } from "react-hook-form";
import { login } from "../actions";
const LoginForm = () => {
const form = useForm({
defaultValues: {
email: "",
password: "",
},
reValidateMode: "onSubmit",
});
const {
...
handleSubmit,
} = form;
return(
<form onSubmit={handleSubmit(login)>
...
<button type="submit">submit</button>
</form>
)
}
我还确保了数据库字符串并且
XAMPP
正在运行,即使出现错误(例如数据库名称或用户错误),我仍然应该得到响应,我错了吗?
Next.js 服务器操作不像传统 HTTP 方法那样直接支持 HTTP 响应代码。相反,您必须返回一个包含 status(或 statusCode)属性的纯 JavaScript 对象来指示响应状态。 例如:
return { status: false, statusCode: 404, message: "My Message" };
要在客户端正确处理响应,请使用await将服务器操作函数视为异步函数:
const myResult = await myServerAction();
这允许您从返回的对象中提取状态、状态代码和消息,并在客户端逻辑中相应地处理响应。 您可以使用反应查询挂钩来获取加载,也可以向其他帮助程序发出错误。