QQ音乐api文档地址:QQ音乐api文档
封装好后的api文件地址:需要引入请求封装文件…/ajax.js
https://github.com/1015770492/yumbo-vue/blob/master/src/api/music/qq/qqmusicApi.js
向将axios请求封装
- npm install axios -s
-
封装的请求函数文件,通过传入type=GET/POST/PUT/DELETE分别发送
axios.get(url)和
axios.post(url,data)
- /*
- ajax请求函数模块
- 返回值: promise对象(异步返回的数据是: response.data)
- 其它请求使用axios.post请求数据,比如type='PUT'
- */
- import axios from 'axios'
- export default function ajax (url, data={}, type='GET') {
-
- return new Promise(function (resolve, reject) {
- // 执行异步ajax请求
- let promise;
- if (type === 'GET') {
- // 准备url query参数数据
- let dataStr = '';
- //数据拼接字符串
- Object.keys(data).forEach(key => {
- dataStr += key + '=' + data[key] + '&'
- });
- if (dataStr !== '') {
- dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
- url = url + '?' + dataStr
- }
- // 发送get请求
- promise = axios.get(url)
- } else {
- // 发送post请求
- promise = axios.post(url, data)
- }
- promise.then(function (response) {
- // 成功了调用resolve()
- resolve(response.data)
- }).catch(function (error) {
- //失败了调用reject()
- reject(error)
- })
- })
- }
-
调用的例子
例如邮箱登录的封装函数
- const apiUrl='http://www.huashengshu.top:3000';//网易云音乐服务器地址,服务器搭建访问前面文档地址:https://binaryify.github.io/NeteaseCloudMusicApi/#/?id=安装
- import ajax from '../../ajax'; //导入封装的axios
- /**
- * 播放链接
- * @param id 歌曲的 songmid,必填,多个用逗号分割,该接口可用 post 或 get
- * 并不是所有的音乐都能获取到播放链接,如果是未登陆或非 vip 用户的 cookie,
- * 只能获取到非 vip 用户可听的歌曲, 其他像一些必须要购买数字专辑才能收听的歌曲,
- * 如果未购买也是无法获取的,无法获取到的播放链接则不会在返回的对象中出现,
- * 这点需要大家自己做好兼容,我这里服务器会默认使用自己会员的 cookie,如果需要使用自己的 cookie,请参考上面文档
- * @returns {Promise | Promise<unknown>}
- */
- export const reqSongUrls = (id)=>ajax(`${apiUrl}/song/urls/`,{id});
-
- import {reqSongUrls} from "@/api/music/qq/qqmusicApi";//导入函数
- //调用邮箱登录函数
- async test() {
- const result = await reqSongUrls('0039MnYb0qxYhV,004Z8Ihr0JIu5s');
- console.log(result);//获得到的数据result
- }
-