概述

  • HBuilderX 2.5.1
  • uniapp中提供了uni.request进行向http请求数据(可以理解为ajax请求)。
  • uni.request 不支持 jsonp。
  • 一种办法是:在uni-app 的项目中 manifest.json文件中配置跨域代理

manifest.json编辑

使用源码视图进行编辑
在这里插入图片描述

manifest.json文件配置

在manifest.json中编辑h5节点(没有可以手动添加):

"h5" : {
        "devServer" : {
            "port" : 80,
            "disableHostCheck" : true,
            "proxy" : {
                "/api" : {
                    "target" : "http://xxx.mydomain.com",
                    "changeOrigin" : true,
                    "secure" : false
                }
            }
        }
    }

调用

接口地址:http://xxx.mydomain.com/api/getCity

uni.request({
	url: '/api/getCity',
	method: 'GET',
	data: {},
	success: res => {console.log(JSON.stringify(res))},
	fail: () => {},
	complete: () => {}
});

特殊说明一下

manifest.json文件中配置的proxy信息为如下时:

"h5" : {
        "devServer" : {
            "port" : 80,
            "disableHostCheck" : true,
            "proxy" : {
                "/api" : {
                    "target" : "http://xxx.mydomain.com",
                    "changeOrigin" : true,
                    "secure" : false
                }
            }
        }
    }

表示以/api开头的请求前面添加上http://xxx.mydomain.com。比如uni.request请求/api/getCity,则实际请求地址为http://xxx.mydomain.com/api/getCity

如果我的接口地址没有前缀怎么办?比如是这样的:http://api.mydomain.com/getCityhttp://api.mydomain.com/getUser。可以使用pathRewrite进行path重写。可以这样配置:

"h5" : {
        "devServer" : {
            "port" : 80,
            "disableHostCheck" : true,
            "proxy" : {
                "/api" : {
                    "target" : "http://xxx.mydomain.com",
                    "changeOrigin" : true,
                    "secure" : false,
                    "pathRewrite":{"^/api":""}
                }
            }
        }
    }

这样配置后,uni.request请求/api/getCity,则实际请求地址为http://xxx.mydomain.com/getCity

再特殊说明一下

HBuilderX支持热部署。但,不通过HBuilderX修改manifest.json文件时,则不会热部署。修改完manifest.json文件后,手动重新发布H5 app才能生效。

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐