ReactNative 下 fetch 重定向无法拦截的解决方案

  • ~2.21K 字
  • 次阅读
  • 条评论

在 RN 开发中,我需要请求 http://connect.rom.miui.com/generate_204 来检测网络通断,该 /generate_204 API 在网络通畅时会返回 204 No Content 响应,但当网关要求进行认证时,会劫持该 HTTP 请求并重定向到登录页面。

但当我使用 fetch 来实现该逻辑时,发现即使产生了重定向,fetch 返回的状态码仍为 200,使用的部分代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
const nasId = await fetch("http://connect.rom.miui.com/generate_204", {
redirect: "manual",
headers: { "Connection": "close" },
}).then(
(response) => {
console.log(`${response.status} ${response.url}`); // debug

return response.status === 204
? null
: new URL(response.url).searchParams.get("nasId");
}
);

运行结果如下图:

使用 ReactNative fetch 的运行结果

从图中可以看到,当网络通畅时,response.status204,被网关劫持时为 200response.url 始终为 http://connect.rom.miui.com/generate_204

但通过抓包发现该请求确实有被正确重定向:

抓包结果

那问题大概率就出在 RN 的 fetch 上了

通过查找 RN 的官方文档,发现 RN 的 fetch 不支持 redirect: manual,如下图:

不支持 redirect: manual

要想在 RN 中拦截重定向,就只能通过 react-native-tcp-socket 手动构造一个 HTTP 请求,然后直接解析 Location 头来解析重定向的 URL,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import TcpSocket from "react-native-tcp-socket";

function getNasId(): Promise<string | null> {
return new Promise((resolve, reject) => {
const socket = TcpSocket.createConnection(
{ host: "connect.rom.miui.com", port: 80 },
() => {
socket.write(
"GET /generate_204 HTTP/1.0\r\nHost: connect.rom.miui.com\r\nConnection: close\r\n\r\n",
);
},
);

let data = "";
socket.on("data", (chunk) => {
data += chunk.toString();
});

socket.on("close", () => {
const location = data.match(/Location:\s*(.*)/i);
if (!location) {
resolve(null);
return;
}

try {
const url = new URL(location[1].trim());
resolve(
url.searchParams.get("nasId") ??
url.pathname.split("/").pop() ??
null,
);
} catch {
resolve(null);
}
});

socket.on("error", (error) => {
socket.destroy();
reject(error);
});
});
}
赞助喵
非常感谢您的喜欢!
赞助喵
分享这一刻
让朋友们也来瞅瞅!