Next有一个内置的API路由https://nextjs.org/docs/api-routes/introduction
它使用/pages/api
是否可以将默认路径从/api/*更改为其他路径,如/myApi/*?
我正在考虑将其添加到exportPathMaphttps://nextjs.org/docs/api-reference/next.config.js/exportPathMap
有什么建议吗?
我相信您无法更改/api
路径,因为Next.js在那个位置看起来很特别。
export function isAPIRoute(value?: string) {
return value === '/api' || Boolean(value?.startsWith('/api/'))
}
如果希望/api
目录与/pages
中的任何其他目录一样工作,可以使用"重写"。它可能看起来如下:
//next.config.js
module.exports = {
async rewrites() {
return [{ source: '/api/:path*', destination: '/another-directory/:path*' }]
},
}
在这种情况下,对/api
的请求将服务于/another-directory
的内容。
或者,您可以为API路由创建自定义服务器,但请注意,您可能需要禁用或覆盖默认文件系统路由。
有关更多信息,请参阅以下Next.js文档:
- 自定义服务器
- 禁用文件系统路由
- RFC:自定义路由