1.调整 manifest.json(设置代理)
"h5" : { "devServer" : { "https" : false, "port" : 8080, "proxy": { "/webapi": { "target": "http://192.168.1.39:8888", "changeOrigin": true, "secure": false, "pathRewrite": { "^/webapi": "/" } } } } }
2.新建文件utils 创建 request.js ,api-method.js
//request.js import store from '../store/index.js'; //vuex //服务地址 let server_url = 'http://localhost:8080'; //使用代理这里需要改成本机地址 let base_url = '/gfweb'; //请求地址 let token = ''; //凭证 let NeedToken = true //'yes' or 'no' 是否需要token // process.env.NODE_ENV === 'development' ? '192.168.0.1' : 'http://***/api' ; //环境配置 function service(options = {}) { /** * 从vuex中获取登录凭证 */ store.state.user.token && (token = store.state.user.token); /** * 判断是否请求路径需要token * @options.NeedToken ('yes' | 'no') * @NeedToken (true | false) */ NeedToken = options.NeedToken == 'no' ? false : true // console.log(`${options.url} === ${options.NeedToken} === ${NeedToken}`) // *** 处理请求配置options *** options.url = `${server_url}${base_url}${options.url}`; //配置请求头 options.header = { 'content-type': 'application/x-www-form-urlencoded', 'accessToken': NeedToken ? `${token}` : '' //Bearer //根据 NeedToken 判断是否需要传token }; return new Promise((resolved, rejected) => { //成功 options.success = (res) => { if (Number(res.data.code) !== 200) { //请求成功 if (Number(res.data.code) == 401) { //登陆失效 store.commit("app/SET_NEED_LOGIN", true) uni.showModal({ title: "重新登陆", content: `${res.data.message}`, success: function(result) { if (result.confirm) { store.commit("user/SET_TOEKN", '') store.commit("user/SET_MEMBER_ID", '') /** * 重定向刷新页面 */ // console.log('vuex保存的重定向地址',store.state.app.redirectPage) wx.navigateTo({ url: '/pages/Login/Login', }); } else if (result.cancel) { // console.log('用户点击取消'); } } }) } else { uni.showToast({ icon: 'none', duration: 3000, title: `${res.data.message}` }); } } // rejected(res.data.message);//错误 resolved(res.data); } //错误 options.fail = (err) => { rejected(err); //错误 } // console.log("请求Options",options) uni.request(options); }); } export default service;
//api-method.js import request from "./request.js" import qs from 'qs' // **noneToken请求 export const NoTokenRequest = (url, data,method) => { const NeedToken = 'no'//是否需要token //'yes' or 'no' return request({ url: url, method: method.toUpperCase(), data, NeedToken }) } // **get请求 export const getRequest = (url, data) => { return request({ url: url, method: 'GET', data }) } // **post请求 export const postRequest = (url, data) => { return request({ url: url, method: 'POST', data }) }
3.封装调用方法 根目录创建API文件夹创建index.js
import { NoTokenRequest, getRequest, postRequest } from "@/utils/api-method.js" // 登陆 export const login = (params) => { return NoTokenRequest('/szgf/app/login/appLogin', params, 'POST') }
4.VUE文件调用接口
import{ login } from "../../api/index.js" login(params).then(res=>{ if(res.code==200){ console.log('success') }else{ } console.log('0000000') });
以上内容由“WiFi之家网”整理收藏!。
原创文章,作者:192.168.1.1,如若转载,请注明出处:https://www.224m.com/232202.html