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

Expo开发模式下,如何解析服务器重定向到RN客户端的查询参数

解决Expo Router + Supabase重定向后仅能获取第一个查询参数的问题

一、优先排查服务器端URL编码问题

你的服务器代码直接拼接email和token到URL中,如果token包含&、=或其他特殊字符,会直接破坏查询字符串结构,导致后续参数被截断。必须对参数进行URL编码:

// 替换服务器端的拼接逻辑
const encodedEmail = encodeURIComponent(email);
const encodedToken = encodeURIComponent(token);
const address = `${next}?email=${encodedEmail}&token=${encodedToken}`;
res.redirect(303, address);

二、Expo Router端的参数解析处理

1. 冷启动场景(应用完全关闭后通过链接打开)

在根布局文件(如_layout.js)中先获取初始URL,手动解析参数后再跳转至目标页面:

import { useEffect } from 'react';
import { Linking } from 'react-native';
import { useRouter } from 'expo-router';

export default function RootLayout() {
  const router = useRouter();

  useEffect(() => {
    const parseInitialLink = async () => {
      const initialUrl = await Linking.getInitialURL();
      if (!initialUrl) return;

      const urlParams = new URLSearchParams(new URL(initialUrl).search);
      const email = urlParams.get('email');
      const token = urlParams.get('token');

      if (email && token) {
        router.push({
          pathname: '/AuthScreen',
          params: { email, token }
        });
      }
    };
    parseInitialLink();
  }, []);

  // 其他布局代码...
}

2. 热启动场景(应用后台运行时通过链接唤醒)

添加链接监听事件,处理后台唤醒时的参数解析:

useEffect(() => {
  const handleDeepLink = ({ url }) => {
    if (!url) return;

    const urlParams = new URLSearchParams(new URL(url).search);
    const email = urlParams.get('email');
    const token = urlParams.get('token');

    if (email && token) {
      router.push({
        pathname: '/AuthScreen',
        params: { email, token }
      });
    }
  };

  const subscription = Linking.addEventListener('url', handleDeepLink);
  return () => subscription.remove();
}, [router]);

3. 在AuthScreen中获取参数

确保目标页面通过useLocalSearchParams正确接收参数:

import { useLocalSearchParams } from 'expo-router';

export default function AuthScreen() {
  const { email, token } = useLocalSearchParams();
  // 此时应能正常获取两个参数
  console.log('邮箱:', email, 'Token:', token);

  // 重置密码逻辑...
}

三、验证深度链接配置

检查app.json中的scheme配置是否正确,服务器端的next参数需匹配该scheme:

{
  "expo": {
    "scheme": "yourappscheme", // 例如你的应用scheme为myapp,链接格式应为myapp://AuthScreen?xxx
    // 其他配置...
  }
}

服务器端的next参数应填写完整的scheme路径(如yourappscheme://AuthScreen),而非仅相对路径/AuthScreen,否则会导致链接解析异常。

四、测试建议

  1. 直接在浏览器访问服务器/auth/confirm端点,确认重定向后的URL参数是否完整且编码正确。
  2. 使用Android命令行测试深度链接:
adb shell am start -W -a android.intent.action.VIEW -d "yourappscheme://AuthScreen?email=test@example.com&token=abc123def"

内容的提问来源于stack exchange,提问作者Yafim Simanovsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:57:27