Expo+React Native安卓端POST请求报错:无法解析主机地址
问题详情
我在App中尝试发送POST请求获取用户令牌,该功能在WEB版本(相同代码)和HTTP客户端Bruno中均可正常工作,但App里始终失败。
API地址格式类似http://example.org.br:3550/,我已经在app.json中添加了usesCleartextTraffic配置:
[ "expo-build-properties", { "android": { "usesCleartextTraffic": true } } ],
我的登录函数代码如下:
export async function login(userName: string, password: string) { console.log('username:', userName) await apiV1 .post('/account/login', { userName, password, }) .then(function (response) { console.log(response) return response }) .catch(function (error) { console.log(error) if (error.response) { console.log('error data: ', error.response.data) console.log(error.response.status) console.log(error.response.headers) } else if (error.request) { console.log(JSON.stringify(error.request, null, 2)) } else { // 请求配置过程中触发错误 console.log('Error', error.message) } }) }
得到的报错信息(关键内容已翻译):
LOG [AxiosError: 网络错误] LOG { "UNSENT": 0, "OPENED": 1, "HEADERS_RECEIVED": 2, "LOADING": 3, "DONE": 4, "readyState": 4, "status": 0, "timeout": 2000, "withCredentials": true, "upload": {}, "_requestId": null, "_subscriptions": [], "_aborted": false, "_hasError": true, "_headers": { "accept": "application/json, text/plain, */*", "content-type": "application/json" }, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey": "network_XMLHttpRequest_http://example.org.br:3550/v1/account/login", "_responseType": "", "_response": "无法解析主机\"example.org.br\":没有与主机名关联的地址", "_sent": true, "_url": "http://example.org.br:3550/v1/account/login", "_timedOut": false, "_trackingName": "unknown", "_incrementalEvents": false, "_performanceLogger": { "_timespans": { "network_XMLHttpRequest_http://example.org.br:3550/v1/account/login": { "startTime": 301157564.214717 } }, "_extras": {}, "_points": { "initializeCore_start": 301155072.756717, "initializeCore_end": 301155229.869617 }, "_pointExtras": {}, "_closed": false } }
排查与解决步骤
检查DNS解析与网络连通性
- 用手机浏览器直接访问
http://example.org.br:3550/,确认是否能正常加载 - 若浏览器也无法访问,切换网络(WiFi/移动数据)测试,排除网络环境问题
- 尝试手动设置手机DNS为公共DNS(如8.8.8.8),清除本地DNS缓存
- 用手机浏览器直接访问
验证Expo配置有效性
- 确保已安装
expo-build-properties插件:执行npx expo install expo-build-properties - 检查app.json中
plugins数组内的配置格式是否正确,无语法错误 - 配置修改后,执行
npx expo prebuild --clean清理旧构建文件,重新编译项目
- 确保已安装
核对API地址配置
- 确认App中Axios实例的baseURL与WEB版完全一致,无域名、端口拼写错误
- 若API为内网服务,确保手机与服务器处于同一局域网,且服务器端口对外开放
调整Axios配置
尝试延长超时时间或关闭跨域凭证(若不需要):import axios from 'axios'; const apiV1 = axios.create({ baseURL: 'http://example.org.br:3550/v1', timeout: 10000, // 延长至10秒超时 withCredentials: false // 无需跨域Cookie时关闭 });
内容的提问来源于stack exchange,提问作者JoyGuilherme
相关产品推荐
相关产品推荐

