英文:
Why doesn't use server work in Next.js 13.4?
问题
我通过声明使用服务器编写了一个函数,代码如下:
Cookies 只能在服务器操作或路由处理程序中进行修改。了解更多信息:https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
我一直在收到这个错误。
可能的原因是什么?
import { cookies } from "next/dist/client/components/headers";
type SearchParams = {
searchParams: {
code: string;
};
};
export default async function EmailLoginPage({ searchParams }: SearchParams) {
await testCookie();
async function testCookie() {
"use server";
cookies().set("test", "test");
}
return <></>;
}
英文:
I wrote a function by declaring use server with code like this,
Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
I keep getting this error.
What could be the reason?
import { cookies } from "next/dist/client/components/headers";
type SearchParams = {
searchParams: {
code: string;
};
};
export default async function EmailLoginPage({ searchParams }: SearchParams) {
await testCookie();
async function testCookie() {
"use server";
cookies().set("test", "test");
}
return <></>;
}
答案1
得分: 1
> 谢谢,但是出现了同样的问题。错误:只能在服务器操作或路由处理程序中修改 Cookie。
这里有两个问题:
- 你错误地导入了
cookies
。 - 只能使用
action
或formAction
属性来调用服务器操作。
以下是更新后的代码:
import { cookies } from "next/headers";
type SearchParams = {
searchParams: {
code: string;
};
};
export default async function EmailLoginPage({ searchParams }: SearchParams) {
async function testCookie() {
"use server";
cookies().set("test", "test");
}
return (
<form action={testCookie}>
<input placeholder="email" name="email" type="text" autoFocus required/>
<input placeholder="password" name="password" type="password" required/>
<button type="submit">Login</button>
</form>
);
}
更多关于 服务器操作 的信息。
英文:
> Thanks, but It occurs same problem. Error: Cookies can only be modified in a Server Action or Route Handler.
There are two things are going wrong here:
- You're importing
cookies
wrong. - Server Actions can only be called using the
action
orformAction
prop.
Here's the updated code:
import { cookies } from "next/headers";
type SearchParams = {
searchParams: {
code: string;
};
};
export default async function EmailLoginPage({ searchParams }: SearchParams) {
async function testCookie() {
"use server";
cookies().set("test", "test");
}
return (
<form action={testCookie}>
<input placeholder="email" name="email" type="text" autofocus required/>
<input placeholder="password" name="password" type="password" required/>
<button type="submit">Login</button>
</form>
);
}
Read more about server actions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论