我无法在新的 nextjs 项目中调用我的路线 API (404)。
我的路线API位于src/app/api/speed.js
在我的页面 src/app/page.tsx 中,我这样做:
fetch("api/speed").then(res=>res.json).then(data=>alert(data.message))
但是在网络开发工具选项卡中,我总是在 GET http://localhost:3000/api/speed 上得到 404
src/app/api/speed.js:
export default function handler (_req,res) {
res.status(200).json({ message: "hey" })
}
src/app/page.tsx
'use clients;
export default function Home() {
function handleClick() {
fetch("api/speed").then(res=>res.json.then(({message})=>alert(message))
}
return (
<><main><div onClick={handleClick}>HEY</div></main><>
)
}
注意,如果我将API路由移动到:src/app/api/speed/route.js,它会起作用,但文档清楚地给出了示例:pages/api/hello.js,所以我不明白为什么这不起作用。
注2:如果是API,我还必须修改代码。官方文档给出了一个不起作用的示例(可能已弃用)。新代码:
import {NextResponse} from "next/server";
export async function GET(req) {
return NextResponse.json({message: "hey"})
}
我想念什么?
如果您想在应用程序路由器中拥有 API 路由器,则必须创建一个名为
route.js/ts
的文件,并使用方法名称导出处理函数。像这样:
export const GET = () => {
return Response.json({ data: "hello world" })
}
现在您可以按照之前的方式获取数据了!
fetch("api/speed")
.then(res=> res.json())
.then(({ data }) => console.log(data))
有关更多信息,您可以阅读文档