NextJS SSR模式下req.url返回错误URL,如何获取localhost真实URL?
问题:Next.js SSR页面中如何获取真实访问URL?
我在产品卡片上设置了指向'/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000'的链接,在自定义产品页面[product].js中使用SSR调用后端API,需要传递当前URL以获取产品详情。但通过NextJS提供的req.url获取到的内容为'/_next/data/development/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000.json?product=hansgrohe-croma-100-shower-set-100-4jet-vario-27592000',请问在localhost环境下如何获取真实的URL?
代码示例:
const fullUrl = req.url; console.log(fullUrl); // 输出 '/_next/data/development/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000.json?product=hansgrohe-croma-100-shower-set-100-4jet-vario-27592000'
解决方案
方法1:使用context.resolvedUrl(官方推荐)
在getServerSideProps的context参数中,resolvedUrl属性直接提供了用户实际访问的路径,无需额外解析:
export async function getServerSideProps(context) { // 获取相对路径 const realPath = context.resolvedUrl; console.log(realPath); // 输出 '/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000' // 拼接localhost环境下的完整URL const fullRealUrl = `http://${context.req.headers.host}${realPath}`; // 调用后端API时传递该URL const response = await fetch(`你的后端API地址?url=${encodeURIComponent(fullRealUrl)}`); const productData = await response.json(); return { props: { productData } }; }
这个方法是Next.js为SSR场景专门提供的属性,兼容性和可靠性最高。
方法2:解析req.url路径
如果无法直接使用resolvedUrl,可以通过字符串处理从Next.js的内部路径中提取真实路由:
export async function getServerSideProps(context) { const { req } = context; const urlObj = new URL(req.url, `http://${req.headers.host}`); // 提取_next/data后的路径并去掉.json后缀 const pathSegment = urlObj.pathname.split('/_next/data/')[1]?.split('.json')[0]; if (!pathSegment) return { props: {} }; // 去掉环境标识(如development),拼接真实路径 const realPathParts = pathSegment.split('/'); const realPath = `/${realPathParts.slice(1).join('/')}`; const fullRealUrl = `http://${req.headers.host}${realPath}`; console.log(fullRealUrl); // 输出 'http://localhost:3000/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000' // 后续API调用逻辑... return { props: {} }; }
方法3:利用req.headers.referer(仅适用于跳转场景)
如果用户是从其他页面跳转过来的,请求头的referer字段会包含上一页的完整URL,但直接在地址栏输入时该字段为空:
export async function getServerSideProps(context) { const { req } = context; const realUrl = req.headers.referer; console.log(realUrl); // 输出 'http://localhost:3000/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000'(仅跳转场景有效) // 后续API调用逻辑... return { props: {} }; }
内容的提问来源于stack exchange,提问作者Mohammed Ismail
相关产品推荐
相关产品推荐

