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

问题描述 投票:0回答:1

我想在 Next.js 1 上使用 SWR 来使用 Google Analytics API,但路线返回 404。

const { data: visitors } = useSWR("/api/dash/route", fetcher);

我的文件夹树:

应用程序/分析/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/”调用api路线”
  • 在组件上使用代码

在浏览器控制台上:

next.js google-analytics-api next.js13 swr
1个回答
0
投票

试试这个:

不要向

http://localhost:3000/api/dash/route
提出请求,而是向
http://localhost:3000/api/dash

提出请求

不要更改文件结构

检查这个沙箱并尝试点击

api/dash
路线。

© www.soinside.com 2019 - 2024. All rights reserved.