diff --git a/src/api/http.js b/src/api/http.js new file mode 100644 index 0000000..7b203bb --- /dev/null +++ b/src/api/http.js @@ -0,0 +1,47 @@ +import {useUserStore} from "../stores/modules/user"; + +const baseURL = "https://www.httpbin.org" + +const httpInterceptor = { + invoke(options){ + // 正则检查是否为http/https开头的url, 如果不是则加上baseURL + if(!options.url.match(/^https?:\/\//)){ + options.url = baseURL + options.url + } + + // 设置超时时间 10 秒 + options.timeout = 10 * 1000 + + // 设置请求头 + options.header = { + ...options.header, + "source-client": "mp-app" + } + + const userStore = useUserStore() + const token = userStore.userInfo?.token + if(token){ + options.header.Authorization = token + options.header.token = token + } + }, + fail(err){ + console.error("请求失败", err) + }, + returnValue(results) { + return new Promise((resolve, reject)=>{ + results.then(resp=>{ + console.log("请求结果", resp) + if(resp.statusCode >= 400){ + console.error("请求失败", resp) + reject(resp) + } else { + resolve(resp) + } + }) + }) + } +} + +uni.addInterceptor("request", httpInterceptor) +uni.addInterceptor("uploadFile", httpInterceptor) diff --git a/src/main.js b/src/main.js index dcea265..5b93e7a 100644 --- a/src/main.js +++ b/src/main.js @@ -1,5 +1,5 @@ import App from './App' - +import "./api/http" import pinia from './stores' // #ifndef VUE3 diff --git a/src/pages/index/index.vue b/src/pages/index/index.vue index 59ebf06..24632a6 100644 --- a/src/pages/index/index.vue +++ b/src/pages/index/index.vue @@ -41,12 +41,14 @@ {{ now }} + + {{ request.ip }} + diff --git a/src/stores/modules/user.js b/src/stores/modules/user.js index 4433355..f15df42 100644 --- a/src/stores/modules/user.js +++ b/src/stores/modules/user.js @@ -5,11 +5,13 @@ export const useUserStore = defineStore('user', () =>{ const userInfo = reactive({ id: "", name: "", + token: "", }) function clearUserInfo() { userInfo.id = "" userInfo.name = "" + userInfo.token = "" } return {