我正在使用 NextJS 14 App Router,并且我的 API 有多个路由处理程序,但我很惊讶地知道我的朋友能够使用 Postman 从他的 PC 向我的路由处理程序发送请求。
我认为默认情况下它们受到保护,因为 NextJS 中的标头遵循同源策略。
但显然,CORS(跨源资源共享)和SOP(同源策略)是客户端决定是否强制执行的服务器端配置。邮递员不强制执行它们。
那么,有没有办法阻止从我的网站外部访问我的路由处理程序?
这是我的代码。
// Client component || Form.tsx
async function sendText(text: string) {
const translateResponse = await fetch("/api/translate-text", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: text,
}),
});
const translatedData = await translateResponse.json();
}
// api/translate-text/route.ts
export async function POST(request: Request) {
const { text} = await request.json();
const res = await fetch(
`https://api-source.com`,
{
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
"Key": process.envAPI_KEY || "",
"Host": process.env.API_HOST || "",
},
body: new URLSearchParams({
from: "auto",
to: "en",
text: text,
}),
}
);
const translatedText = await res.json();
return NextResponse.json(translatedText, {
status: 201,
});
}
确保您在文件中使用
use-client
和 use-server
标头
这确保它们在正确的位置运行
https://nextjs.org/docs/app/building-your-application/rendering/server-components