在NextJS 14上找不到API路由(应用程序/路由)

ars1skjm  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(219)

我想在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
  • 在组件上使用代码

在浏览器控制台上:


abithluo

abithluo1#

试试这个:
不要向http://localhost:3000/api/dash/route发出请求,而是向http://localhost:3000/api/dash发出请求

不要更改文件结构

检查this sandbox并尝试访问api/dash路由。

相关问题