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.
master
pan93412 4 years ago committed by GitHub
parent c860745bfe
commit bce09351cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -44,7 +44,7 @@ git clone https://github.com/qier222/YesPlayMusic.git
npm install npm install
``` ```
4. 替换 `/src/utils/request.js` 里面 `baseURL` 的值为网易云 API 地址 4. 替换 `/src/config/request.js` 里面 `baseURL` 的值为网易云 API 地址
```JS ```JS
baseURL: "http://example.com", baseURL: "http://example.com",

@ -0,0 +1,6 @@
/**
* The base url of your API.
*
* The API can be found at https://github.com/Binaryify/NeteaseCloudMusicApi
*/
export const baseURL = "";

@ -1,31 +1,40 @@
import axios from "axios"; import axios from "axios";
import { baseURL } from "@/config/request";
const service = axios.create({ const service = axios.create({
baseURL: "/api", baseURL: baseURL,
withCredentials: true, withCredentials: true,
timeout: 15000, 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( service.interceptors.response.use(
(response) => { (response) => {
const res = response.data; const res = response.data;
if (res.code !== 200) { if (res.code !== 200) {
if (res.code === 401) { alert(
alert("token expired"); errors.has(res.code)
} else if (res.code === 502) { ? errors.get(res.code)
alert(res.msg); // null = `The server returned ${res.msg}`
} else if (res.code === 301) { || `The server returned ${res.msg}`
alert("login required"); // -1 = default expection message
} else { : errors.get(-1) + res.code
alert("unknown error"); );
}
} else { } else {
return res; return res;
} }
}, },
(error) => { (error) => {
console.log("err" + error); const errMsg = `error: ${error}`;
alert("err " + error); console.log(errMsg);
return Promise.reject(error); return Promise.reject(error);
} }
); );

Loading…
Cancel
Save