部署到 Netlify 时,基于 IP 国家/地区代码的 Nuxt 3 中间件重定向不起作用

问题描述 投票:0回答:1

我尝试在 IP 地址查找后根据用户的国家/地区代码将流量转发到特定的 slug。

它在本地运行得很好,但当我部署到 Netlify 时却不起作用。

export default defineNuxtRouteMiddleware(async (to, from) => {
  const targetPathDe = '/de-de'
  const targetPathEn = '/de-en'

  // Prevent middleware from redirecting if already on the target path
  if (to.path === targetPathDe || to.path === targetPathEn) {
    return
  }

  const ipApiUrl = 'http://ip-api.com/json/?fields=countryCode'

  try {
    // Use native fetch to get IP data
    const response = await fetch(ipApiUrl)
    const ipData = await response.json()

    // Check the country code from IP data
    if (ipData.countryCode === 'DE') {
      return navigateTo(targetPathDe)
    } else {
      return navigateTo(targetPathEn)
    }
  } catch (error) {
    console.error('Error fetching IP data:', error)
    return navigateTo(targetPathEn)
  }
})

在本地,我正在运行

npm run dev
,Netlify 是
npm run build

nuxt.js middleware netlify nuxtjs3
1个回答
0
投票

OP 目前考虑使用地理定位边缘函数
它更容易实现,也可能更精确!

© www.soinside.com 2019 - 2024. All rights reserved.