在基础文件里面创建一个api文件 在创建两个 js文件
http.js 里面封装 request 请求
let baseUrl = 'https://white.51.toponet.cn'; //基地址
export const request = (options = {}) => {//异步封装接口,使用Promise处理异步请求return new Promise((resolve, reject) => {// 发送请求uni.request({url: baseUrl + options.url || '', method: options.method || 'GET', data: options.data || {}, header:{"x-requested-with":"XMLHttpRequest","content-type": "application/x-www-form-urlencoded","Access-Control-Allow-Origin":"*","token":uni.getStorageSync('token') //token}}).then(res => {let {data} = res;resolve(data);}).catch(error => {reject(error);})})
}
在 service.js 封装要调用的接口
import { request } from './http.js'; //导入封装好的js文件//每一个请求的接口都返回一个函数,便于直接调用//请求登录的接口
export const login = (data)=>{return request({url:'/api/user/login', method:'post',data,})
}//请求首页的接口
export const register = ()=>{return request({url:"/api/index/index", method:'get'})
}
在页面 引入接口文件
import {login} from '../../api/service.js'// 登录接口async getList() {const res = await login(this.form)console.log(res, 1);if (res.code != 1) {uni.showToast({title: res.msg,icon: 'error'})} else {uni.setStorageSync('token', res.data.token)//保存tokensetTimeout(() => {uni.navigateTo({url: '/subpkg/jumpPage/jumpPage'})}, 1000)}},