uni-app在H5使用uni.request请求报错{"errMsg":"request:fail"}

uni-app在H5使用uni.request请求报错{“errMsg”:“request:fail”}

项目属性
产品分类 uniapp/H5
PC开发环境操作系统 Windows
PC开发环境操作系统版本号 24H2
HBuilderX类型 正式
HBuilderX版本号 4.76
浏览器平台 微信内置浏览器
项目创建方式 HBuilderX

示例代码:

try {
    const [error, response] = await new Promise((resolve) => {
        uni.request({
            url: `http://47.96.7.237:30018/?method=userquery&openid=${this.openid}`,
            method: 'GET',
            header: {
                'Content-Type': 'application/json'
            },
            success: (res) => {
                resolve([null, res]);
            },
            fail: (err) => {
                resolve([err, null]);
            }
        });
    });

    if (error) {  
        console.error('请求失败:', error);  
        this.userInfoError = '请求失败,请稍后重试: ' + JSON.stringify(error);  
        this.bindStatus = 'unbound';  
        return;  
    }  

    console.log('响应数据:', response);  
    alert(response.data.msg);  

    if (response.data && response.data.msg === 'ok' && response.data.result) {  
        this.userInfo = {  
            name: response.data.result.name || '',  
            idno: response.data.result.idno || '',  
            tel: response.data.result.tel || ''  
        };  

        if (response.data.result.name && response.data.result.idno && response.data.result.tel) {  
            this.bindStatus = 'bound';  
        } else {  
            this.bindStatus = 'unbound';  
        }  
    } else {  
        this.bindStatus = 'unbound';  
        this.userInfoError = response.data && response.data.error ?  
            response.data.error :  
            '未查询到用户信息';  
    }  
} catch (error) {  
    console.error('查询用户信息失败:', error);  
    this.userInfoError = '查询失败,请稍后重试: ' + error.message;  
    this.bindStatus = 'unbound';  
} finally {  
    this.loading = false;  
}

bug描述:

在通过uniapp中的uni.request请求时返回错误信息{“errMsg”:“request:fail”}


更多关于uni-app在H5使用uni.request请求报错{"errMsg":"request:fail"}的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复

自己检查拦截器是否做了额外处理,确保接口正常。 uni request 功能稳定没有额外的修改

更多关于uni-app在H5使用uni.request请求报错{"errMsg":"request:fail"}的实战教程也可以访问 https://www.itying.com/category-93-b0.html


你说的这个“拦截器”是指的什么?

这是一个典型的跨域问题。在H5环境下,uni.request发起的HTTP请求需要遵循浏览器的同源策略。

从你的代码可以看出:

  1. 请求的URL是http://47.96.7.237:30018/,使用了HTTP协议和IP地址
  2. 运行环境是微信内置浏览器

解决方案:

方案一:配置服务器CORS 让后端服务器添加CORS响应头:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS
Access-Control-Allow-Headers: Content-Type

方案二:使用HTTPS协议 将服务器升级为HTTPS,并将请求URL改为:

url: `https://47.96.7.237:30018/?method=userquery&openid=${this.openid}`

方案三:配置HBuilderX的manifest.json 在H5配置中设置代理:

{
  "h5": {
    "devServer": {
      "proxy": {
        "/api": {
          "target": "http://47.96.7.237:30018",
          "changeOrigin": true
        }
      }
    }
  }
}
回到顶部