uniapp Wechat applet encapsulates public request js (api version)

1. Create a new api folder
Create an api folder in the project directory, put the files and index.js folders in it, and put the js request interface
insert image description here
1 and index.js corresponding to each page in the files folder

/**
 * api接口的统一出口
 */
const api = {
    
    };
const requireComponent = require.context('./files', false, /\.js$/)
requireComponent.keys().forEach(fileName => {
    
    
  const componentName = fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
  const componentConfig = requireComponent(fileName)
  api[componentName] = componentConfig.default
})
export default api;

2. For example: login.js

/**
 * 登录用到的接口
 */
import http from '@/utils/http.js'
import config from '@/utils/config.js'
const login = {
    
    
	//角色001-账号登录
	transportLogin(data){
    
    
		return new Promise((resolve, reject) => {
    
    
			http.request({
    
    
				domain:config.adminDomain,//接口ip地址+端口号(第一种)
				url: "/user/login",
				method: "POST",
				data,
				callBack: res => {
    
    
					resolve(res);
				}
			})
		})
	},
	//角色002-账号登录
	regulatorLogin(data){
    
    
		return new Promise((resolve, reject) => {
    
    
			http.request({
    
    
				domain:config.domain,//接口ip地址+端口号(第二种)
				url: "/wx/login",
				method: "POST",
				data,
				callBack: res => {
    
    
					resolve(res);
				}
			})
		})
	}
}
export default login;

2. config.js

const domain = "http://192.888.888.6:80/my"
const adminDomain = "http://192.888.444.9:800"
const adminH5 = "http://192.888.666.7:82/#";
module.exports = {
    
    
	domain,
	adminDomain,
	adminH5
}

3. main.js
insert image description here

4. Page usage

<template>
	<view class="login-btn" @click="toLogin">登录</view>
	<view class="login-btn" @click="toLogin2">登录</view>
</template>
methods: {
    
    
	toLogin(){
    
    
		this.$api.login.transportLogin(data).then(res=>{
    
    
			uni.hideLoading()
			if (res.code === 200) {
    
    
				// 保存登陆信息
				uni.setStorageSync('loginResult', res)
				uni.setStorageSync('token', res.token);
				uni.setStorageSync('login',false);
				uni.reLaunch({
    
    
					url: "/pages/learning/learning"
				})
			}
		})
	},
	toLogin2(){
    
    
		let data = {
    
    
			account: "", //用户名
			pwd: "" //密码
		};
		this.$api.login.regulatorLogin(data).then(res=>{
    
    
			uni.hideLoading()
			if (res.code === 200) {
    
    
				// 保存登陆信息
				uni.setStorageSync('loginResult', res)
				uni.setStorageSync('token', res.token);
				uni.setStorageSync('login',false);
				uni.reLaunch({
    
    
					url: "/pages/learning/learning"
				})
			}
		})
	}
}

Guess you like

Origin blog.csdn.net/maoge_666/article/details/132146574