Next.js 14本地应用集成CVENT API遇404错误,请求技术支援
Next.js 14 集成CVENT API时本地API路由404问题解决
问题核心
前端请求http://localhost:3000/api/cvent-api返回404,说明Next.js的API路由未被正确识别,这是路由规则不匹配导致的,和CVENT API本身无关。
解决方案
1. 确认路由模式并修正API路由路径
Next.js 14支持两种路由模式,API路由规则完全不同:
情况A:使用Pages Router(项目根目录有pages文件夹)
- API路由文件必须放在
pages/api/目录下,注意系统区分大小写时Api和api是不同路径,文件名需统一为小写。 - 将你的
Api/cvent-api.ts文件移动到pages/api/cvent-api.ts,代码无需修改,保持默认导出handler函数即可。
情况B:使用App Router(项目根目录有app文件夹)
- API路由需要以目录+route.ts的形式存在,创建
app/api/cvent-api/route.ts文件,修改代码如下:
import fetch from 'node-fetch' const baseUrl = 'https://api-platform-eur.cvent.com'; async function getAccessToken(): Promise<string> { const encodedCredentials = Buffer.from(`${process.env.CVENT_CLIENT_ID}:${process.env.CVENT_CLIENT_SECRET}`).toString('base64'); const authHeader = `Basic ${encodedCredentials}`; const clientId = process.env.CVENT_CLIENT_ID || ''; const params = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, }); const response = await fetch(`${baseUrl}/ea/oauth2/token`, { method: 'POST', headers: { Authorization: authHeader, 'Content-Type': 'application/x-www-form-urlencoded', }, body: params.toString(), }); if (!response.ok) { throw new Error(`Error fetching access token, status: ${response.status}`); } const data = await response.json(); return data.access_token; } // App Router的API路由需导出对应HTTP方法的函数 export async function GET() { try { const accessToken = await getAccessToken(); console.log(`access token is: ${accessToken}`) const response = await fetch(`${baseUrl}/ea/attendees`, { method: "GET", headers: { "Content-type": "application/json", Authorization: `Bearer ${accessToken}`, } }); if (!response.ok) { throw new Error(`Error fetching attendees list, status: ${response.status}`); } const data = await response.json(); console.log('Data is:', data); return Response.json(data); } catch (error) { console.error(error); return Response.json({ message: 'Internal Server Error' }, { status: 500 }); } }
2. 额外检查项
- 重启Next.js开发服务器:路由变更或环境变量修改后需重启才能生效。
- 验证环境变量加载:在API路由中添加
console.log(process.env.CVENT_CLIENT_ID),确认变量是否正确读取。 - 检查CVENT API端点:根据CVENT文档,
/ea/attendees可能需要指定eventId参数(如/ea/attendees?eventId=xxx),本地路由问题解决后若仍有CVENT端的404,需补充该参数。
前端代码无需修改
你的page.tsx中请求/api/cvent-api的路径是正确的,解决API路由路径问题后即可正常请求。
内容的提问来源于stack exchange,提问作者Cheoncio
相关产品推荐
相关产品推荐

