我使用的是最新版本的nextjs,使用的是App Router。我试图从/api
端点上的下一个API获取数据,但它返回错误500。
错误[ERR_INTERNAL_ASSERTION]:TypeError [ERR_INVALID_THIS]:“this”的值必须是EventTarget类型
这是下一个API文件app/api/route.ts
的内容:
import { NextResponse } from "next/server";
import { NextApiRequest, NextApiResponse } from "next";
export const POST = async (req: NextApiRequest, res: NextApiResponse) => {
console.log(req);
return NextResponse.json({ data: "accessToken" });
};
这就是我在服务器端调用它的方式:
"use client";
import { useSearchParams } from "next/navigation";
export default function Home() {
const authorizeTwitchApp = `${process.env.twitchApiUrl}/oauth2/authorize?response_type=code&client_id=${process.env.twitchClientId}&redirect_uri=http://localhost:3000&scope=channel%3Amanage%3Apolls+channel%3Aread%3Apolls+openid`;
const queryParam = useSearchParams().get("code");
const getAccessToken = async (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
const response = await fetch("http://localhost:3000/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ code: queryParam }),
});
const data = await response.json();
console.log(data);
};
return (
<div>
<a href={authorizeTwitchApp}>click me !!</a>
<button onClick={(e) => getAccessToken(e)}>send code to api !!</button>
</div>
);
}
1条答案
按热度按时间c9qzyr3d1#
我也犯了同样的错误。我从文档https://nextjs.org/docs/app/api-reference/file-conventions/route中了解到。请求以promise的形式接收,之后需要使用方法.json()将其转换为对象