Skip to content

后端接口配置地址


数据服务是一个应用的灵魂,它驱动着应用的各个功能模块的正常运转。我们在common/api(一以下简称api)模块封装了服务端交互,通过 API 的形式可以和任何技术栈的服务端应用一起工作。

服务交互流程

服务交互流程如下:

  • 1.组件内调用 api服务
  • 2.api服务封装请求数据,通过 request.js 发送请求
  • 3.组件获取 api返回的数据,更新视图数据或触发其它行为

自定义封装请求

以登录为例,login.vue 组件内,用户输入账号密码点击登录,接口地址为 /system/jwtLogin,调用自定义封装$http进行post请求,获取登录服务返回的数据,进行后续操作。

this.$http.post('/system/jwtLogin', {}, {
        params: {},
    header: {
        'content-type': 'application/json'
    },
    custom: {auth: false}
}).then(res => {
    if(res.statusCode == 200){  //登录成功
        ....
     } else {  //登录失败
        ....
     }
})

uni-app API请求

uni.request发起网络请求,是uni-app自己的API方法。

uni.request({
    url: this.$baseUrl + '/mdata/user/getCurrentUserInfor',
    method: 'POST',
    header: {
    'content-type': 'application/x-www-form-urlencoded',
    },
    success: res => {   //请求成功
        ...
    },
    fail: function(err) {  //请求失败
        ...
    }
});

请求的 header 中 content-type 默认为 application/json。 避免在 header 中使用中文,或者使用 encodeURIComponent 进行编码。 网络请求的 超时时间 可以统一在 manifest.json 中配置 networkTimeout。

baseUrl配置

你可以在项目根目录下的应用配置文件(common/api/config.js)中配置你的 API 服务 base url 地址及其他地址。

const baseUrl = 'https://vue.misboot.com'                         //基础接口地址
const redirectUrl = 'https://app.misboot.com/#/'                  //回调地址
const upLoadUrl = 'https://vue.misboot.com/document/oss/upload'   //图片上传地址


module.exports = {
    baseUrl,
    redirectUrl,
    upLoadUrl
}

因为在main.js中已经对上述三个地址进行了全局挂载,所以在页面中使用时无需再次引入,直接使用即可

```main.js

Vue.prototype.$redirectUrl = redirectUrl;  //回调地址
Vue.prototype.$baseUrl = baseUrl;  //接口地址
Vue.prototype.$upLoadUrl = upLoadUrl;  //图片上传地址

```  .vue
例如: let url = this.$baseUrl + '/system/qiyeweixin/qywxLogin.api'

致力于为企业信息化品牌建设提供强力驱动