我想在Next.js 1上使用SWR使用Google Analytics API,但路由返回404。
const { data: visitors } = useSWR("/api/dash/route", fetcher);
字符串
我的文件夹树:
x1c 0d1x的数据
app/analytics/page.tsx
"use client";
import useSWR from "swr";
import fetcher from "@lib/fetcher";
export default function Analytics() {
const { data: visitors } = useSWR("/api/dash/route", fetcher);
return (
<div>{visitors?.totalVisitors} {visitors?.days} days</div>
);
}
型
src/app/API/dash/route.ts
import { NextApiRequest, NextApiResponse } from "next";
import { BetaAnalyticsDataClient } from "@google-analytics/data";
const propertyId = process.env.GA_PROPERTY_ID;
const DAYS = 7;
const analyticsDataClient = new BetaAnalyticsDataClient({
credentials: {
client_email: process.env.GA_CLIENT_EMAIL,
private_key: process.env.GA_PRIVATE_KEY?.replace(/\n/gm, '\n'),
},
});
export default async function handler(
_req: NextApiRequest,
res: NextApiResponse
) {
const [response] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dateRanges: [
{
startDate: `${DAYS}daysAgo`,
endDate: "today",
},
],
dimensions: [
{
name: "year",
},
],
metrics: [
{
name: "activeUsers",
},
],
});
let totalVisitors = 0;
response.rows?.forEach((row: any) => {
totalVisitors += parseInt(row.metricValues[0].value);
});
res.setHeader(
"Cache-Control",
"public, s-maxage=43200, stale-while-revalidate=21600"
);
return res.status(200).json({
totalVisitors,
days: 7,
});
}
型
我什么都试过了:
- 将名称更改为“route.ts”/“ga.ts”/“route.js”
- 我已经尝试将“API/route.ts”放在路径中
- 我已经尝试使用“http://localhost:3000/api/dash/route”、“/API/dash/route”、“API/dash/route”、“./API/dash/route”调用API
- 在组件上使用代码
在浏览器控制台上:
的
1条答案
按热度按时间abithluo1#
试试这个:
不要向
http://localhost:3000/api/dash/route
发出请求,而是向http://localhost:3000/api/dash
发出请求不要更改文件结构。
检查this sandbox并尝试访问
api/dash
路由。