如何在我的部署环境中使用Next.js的API路由?

huangapple go评论65阅读模式
英文:

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 &quot;next&quot;;
import { join } from &quot;path&quot;;
import fs from &quot;fs/promises&quot;;
import matter from &quot;gray-matter&quot;;
import { MarkDownProps } from &quot;@/types/pages&quot;;

type Error = {
  error: string;
};

type Data = MarkDownProps[] | Error;

type Send&lt;Data&gt; = (data: MarkDownProps[]) =&gt; void;

type newApiResponse = {
  send: Send&lt;Data&gt;;
  json: Send&lt;Data&gt;;
  status: (statusCode: number) =&gt; NextApiResponse&lt;Data&gt;;
};

export default async function handler(
  req: NextApiRequest,
  res: newApiResponse,
) {
  if (req.method === &quot;GET&quot;) {
    try {
      const result = await getMdList();
      res.status(200).send(result);
    } catch (error) {
      res.status(500).send({ error: &quot;failed to fetch data&quot; });
    }
  }
}

export const getMdList = async () =&gt; {
  ...some code
  return posts;
};

async function getMdFiles(dirPath: string): Promise&lt;string[]&gt; {
  ...some code
  return mdFiles;
}



// Components that use the API
// get markdowns data

const listfetch = async () =&gt; {
    const response = await axios.get(&quot;/api/md&quot;);
    if (pathname.split(&quot;/&quot;)[1] === &quot;blog&quot;) {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) =&gt; item.category === &quot;github&quot;,
        ),
      );
    } else {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) =&gt; item.category === pathname.split(&quot;/&quot;)[1],
        ),
      );
    }
  };

  useEffect(() =&gt; {
    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(&#39;next&#39;).NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  images: {
    unoptimized: true,
  },
  compiler: {
    styledComponents: true,
  },
  pageExtensions: [&quot;js&quot;, &quot;jsx&quot;, &quot;ts&quot;, &quot;tsx&quot;, &quot;md&quot;, &quot;mdx&quot;],
};

module.exports = nextConfig;


how can i resolve this problem??

答案1

得分: 0

无法在静态部署环境中使用 page/api 目录。

英文:

cannot use page/api dir in static deployment envirment

huangapple
  • 本文由 发表于 2023年3月9日 16:22:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定