在request 文件夹 新建request.js
import main from "main.js"
export const request = ( options) = > { return new Promise ( ( resolve, reject) = > { let token = uni. getStorageSync ( 'token' ) options. header. Authorization = tokenuni. request ( { url: main. baseUrl + options. url, data: options. data || { } , method: options. method || 'POST' , header: options. header, success: ( res) = > { if ( res. data. code == 401 ) { uni. navigateTo ( { url: '/ pages/ login/ login'} ) } console. log ( res. data) ; resolve ( res. data) } , fail: ( err) = > { uni. showToast ( { title: '请求接口失败' } ) reject ( err) } , catch : ( e) = > { console. log ( e) ; } } ) } )
}
export default { request
}
在main.js 下添加
export default { baseUrl: "http://192.168.0.18:8081"
}
页面中引用
import request from "@/request/request.js"
绑定事件调用接口
getcodes ( ) { request. request ( { url: '/ getPhoneCode', data: { username: this . username} , header: { 'content- type': ' application/ x- www- form- urlencoded'} , method: 'post' , } ) . then ( res = > { console. log ( "------res------" , res) } ) }