NextJS 13如何移除API路由URL中的api路径前缀?
在Next.js 13 Pages Router中移除API路由的/api前缀
你推测的报错原因完全正确:在Pages Router模式下,pages/目录下的文件默认会被解析为React页面组件,框架会尝试渲染该组件。但你导出的是异步API处理函数,它返回的是Promise,React无法将Promise作为子元素渲染,因此触发了错误。
下面是两种可行的解决方案:
方案一:使用Next.js重写配置(推荐)
这是官方支持的标准方式,无需修改现有API文件的位置,只需在next.config.js中添加重写规则,将/foo/bar的请求内部转发到/api/foo/bar。
修改next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/foo/bar', destination: '/api/foo/bar', }, ]; }, }; module.exports = nextConfig;
配置完成后重启开发服务器,访问http://localhost:8080/foo/bar即可触发原API路由,返回{ foo: "bar2" }的JSON响应。
方案二:在页面文件中兼容API请求(不推荐)
如果一定要将文件放在pages/foo/bar.ts,可以通过getServerSideProps判断请求类型,分别返回JSON响应或页面组件。这种方式会混淆页面与API的职责,仅适合特殊场景。
代码示例:
import { GetServerSideProps } from 'next'; // 页面组件(若需渲染页面则保留) export default function FooBarPage() { return <div>Foo Bar 页面</div>; } export const getServerSideProps: GetServerSideProps = async (context) => { // 根据请求头判断是否为API请求 const isApiRequest = context.req.headers.accept?.includes('application/json'); if (isApiRequest) { // 返回JSON响应 context.res.setHeader('Content-Type', 'application/json'); context.res.statusCode = 200; context.res.end(JSON.stringify({ foo: "bar2" })); return { props: {} }; } // 非API请求则返回页面组件所需的props return { props: {} }; };
内容的提问来源于stack exchange,提问作者Evanss
相关产品推荐
相关产品推荐

