You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中调用API时如何跳转至指定页面?

解决Next.js API路由无法跳转页面的问题

原因

你判断的没错,pages/api下的路由运行在服务端环境,next/navigation是客户端专属的路由工具,服务端无法直接触发页面跳转。

两种可行方案

方案1:服务端直接返回重定向响应

如果是GET请求,可在API路由里用res.redirect()让浏览器跳转:

export default function handler(req, res) {
  console.log("Received Gesture");
  // 跳转到项目内指定页面,比如/target-page
  res.redirect(302, '/target-page');
}
  • 若是POST请求,建议用303状态码,确保跳转后浏览器用GET请求目标页面:res.redirect(303, '/target-page')

方案2:返回跳转指令让客户端处理

如果是前端异步调用API(比如fetch/axios),服务端返回跳转地址,由客户端代码触发路由跳转:

  1. API路由代码:
export default function handler(req, res) {
  console.log("Received Gesture");
  res.status(200).json({ redirectTo: '/target-page' });
}
  1. 客户端调用示例:
import { useRouter } from 'next/navigation';

const callGestureApi = async () => {
  const res = await fetch('/api/your-api-path');
  const data = await res.json();
  if (data.redirectTo) {
    const router = useRouter();
    router.push(data.redirectTo);
  }
};

内容的提问来源于stack exchange,提问作者Mina Nassef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 04:17:41