From bce09351cdb1343e09d864de2e77b6a859273c65 Mon Sep 17 00:00:00 2001 From: pan93412 <28441561+pan93412@users.noreply.github.com> Date: Sun, 18 Oct 2020 11:42:12 +0800 Subject: [PATCH] Make configuring baseURL easier and make the errors friendly (#9) * feat(utils/request): make configuring baseURL easier * docs(config/request): update the corresponding changes 5bc29f9200327de1d8aa23ab383bbd7f115db7ee * feat(utils/request): make the errors friendly I replaced the ugly if-statement with Map, and I also make the message user-friendly since this project is written for users, not only for developers. And also, I removed the useless "alert", it is useless and annoying for users. --- README.md | 2 +- src/config/request.js | 6 ++++++ src/utils/request.js | 33 +++++++++++++++++++++------------ 3 files changed, 28 insertions(+), 13 deletions(-) create mode 100644 src/config/request.js diff --git a/README.md b/README.md index 22d4bc8..b81b731 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ git clone https://github.com/qier222/YesPlayMusic.git npm install ``` -4. 替换 `/src/utils/request.js` 里面 `baseURL` 的值为网易云 API 地址 +4. 替换 `/src/config/request.js` 里面 `baseURL` 的值为网易云 API 地址 ```JS baseURL: "http://example.com", diff --git a/src/config/request.js b/src/config/request.js new file mode 100644 index 0000000..bac58ec --- /dev/null +++ b/src/config/request.js @@ -0,0 +1,6 @@ +/** + * The base url of your API. + * + * The API can be found at https://github.com/Binaryify/NeteaseCloudMusicApi + */ +export const baseURL = ""; \ No newline at end of file diff --git a/src/utils/request.js b/src/utils/request.js index 7c4ae44..7c9c333 100644 --- a/src/utils/request.js +++ b/src/utils/request.js @@ -1,31 +1,40 @@ import axios from "axios"; +import { baseURL } from "@/config/request"; const service = axios.create({ - baseURL: "/api", + baseURL: baseURL, withCredentials: true, timeout: 15000, }); +const errors = new Map([ + [401, 'The token you are using has expired.'], + [502, null], + [301, 'You must login to use this feature.'], + [-1, 'An unexpected error has occurred: '], +]); + service.interceptors.response.use( (response) => { const res = response.data; + if (res.code !== 200) { - if (res.code === 401) { - alert("token expired"); - } else if (res.code === 502) { - alert(res.msg); - } else if (res.code === 301) { - alert("login required"); - } else { - alert("unknown error"); - } + alert( + errors.has(res.code) + ? errors.get(res.code) + // null = `The server returned ${res.msg}` + || `The server returned ${res.msg}` + // -1 = default expection message + : errors.get(-1) + res.code + ); } else { return res; } }, (error) => { - console.log("err" + error); - alert("err " + error); + const errMsg = `error: ${error}`; + console.log(errMsg); + return Promise.reject(error); } );