英文:
How can I use the nextjs API route in my deployment environment?
问题
以下是代码部分的翻译:
// src/pages/api/md/index.ts
// 获取 Markdown 数据
import type { NextApiRequest, NextApiResponse } from "next";
import { join } from "path";
import fs from "fs/promises";
import matter from "gray-matter";
import { MarkDownProps } from "@/types/pages";
type Error = {
  error: string;
};
type Data = MarkDownProps[] | Error;
type Send<Data> = (data: MarkDownProps[]) => void;
type newApiResponse = {
  send: Send<Data>;
  json: Send<Data>;
  status: (statusCode: number) => NextApiResponse<Data>;
};
export default async function handler(
  req: NextApiRequest,
  res: newApiResponse,
) {
  if (req.method === "GET") {
    try {
      const result = await getMdList();
      res.status(200).send(result);
    } catch (error) {
      res.status(500).send({ error: "无法获取数据" });
    }
  }
}
export const getMdList = async () => {
  // ... 一些代码
  return posts;
};
async function getMdFiles(dirPath: string): Promise<string[]> {
  // ... 一些代码
  return mdFiles;
}
// 使用 API 的组件
// 获取 Markdown 数据
const listfetch = async () => {
    const response = await axios.get("/api/md");
    if (pathname.split("/")[1] === "blog") {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) => item.category === "github",
        ),
      );
    } else {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) => item.category === pathname.split("/")[1],
        ),
      );
    }
  };
  useEffect(() => {
    listfetch();
  }, []);
以下是配置部分的翻译:
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  images: {
    unoptimized: true,
  },
  compiler: {
    styledComponents: true,
  },
  pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
};
module.exports = nextConfig;
帮助你解决问题的方法如下:检查部署时的 API 路径是否正确,确保与本地环境相匹配。你还可以在部署环境中查看网络请求是否被正确路由到 /api/md。确保在部署配置中设置了正确的页面扩展名,如你的配置文件所示。如果问题仍然存在,可能需要检查部署环境的网络设置和服务器配置。
英文:
my nextjs version - 13.2.1
First of all, the code below works normally in a local environment.
// src/pages/api/md/index.ts
// get markdowns data
import type { NextApiRequest, NextApiResponse } from "next";
import { join } from "path";
import fs from "fs/promises";
import matter from "gray-matter";
import { MarkDownProps } from "@/types/pages";
type Error = {
  error: string;
};
type Data = MarkDownProps[] | Error;
type Send<Data> = (data: MarkDownProps[]) => void;
type newApiResponse = {
  send: Send<Data>;
  json: Send<Data>;
  status: (statusCode: number) => NextApiResponse<Data>;
};
export default async function handler(
  req: NextApiRequest,
  res: newApiResponse,
) {
  if (req.method === "GET") {
    try {
      const result = await getMdList();
      res.status(200).send(result);
    } catch (error) {
      res.status(500).send({ error: "failed to fetch data" });
    }
  }
}
export const getMdList = async () => {
  ...some code
  return posts;
};
async function getMdFiles(dirPath: string): Promise<string[]> {
  ...some code
  return mdFiles;
}
// Components that use the API
// get markdowns data
const listfetch = async () => {
    const response = await axios.get("/api/md");
    if (pathname.split("/")[1] === "blog") {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) => item.category === "github",
        ),
      );
    } else {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) => item.category === pathname.split("/")[1],
        ),
      );
    }
  };
  useEffect(() => {
    listfetch();
  }, []);
this code is receive data well in local. but not found in deployment
error :GET https://{my URL}/api/md 404
think about what this needed more, i add pageExtensions in next.config but didnt work too
my config is this
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  images: {
    unoptimized: true,
  },
  compiler: {
    styledComponents: true,
  },
  pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
};
module.exports = nextConfig;
how can i resolve this problem??
答案1
得分: 0
无法在静态部署环境中使用 page/api 目录。
英文:
cannot use page/api dir in static deployment envirment
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论