使用jsonp抓取QQ音乐上的数据

1.JSONP的用途和原理

使用JSONP主要是目的通过动态创建Script,动态拼接url,进而抓取数据,实现跨域。确切地说,AJAX请求由于同源影响,是不允许进行跨域请求的,而Script标签src属性中的链接却可以访问跨域的js脚本,利用这一特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的JS代码,在src属性中进行调用,实现跨域。

2.JSONP的使用方法

2.1 引入github的jsonp

打开项目>package.json>在”dependencies”下添加代码

"jsonp": "^0.2.1"

如图所示,然后执行安装cmd指令,并重新运行项目

?

1

2

npm install

 npm run dev

2.2 封装jsonp.js

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import originJSONP from 'jsonp'

export default function jsonp(url, data, option) {

 url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

 return new Promise((resolve, reject) => {

 originJSONP(url, option, (err, data) => {

  if (!err) {

  resolve(data)

  } else {

  reject(err)

  }

 })

 })

}

function param(data) {

 let url = ''

 for (var k in data) {

 let value = data[k] !== undefined ? data[k] : ''

 url += `&${k}=${encodeURIComponent(value)}`

 }

 // 删除第一个&

 return url ? url.substring(1) : ''

}

目录结构如下:

2.3 jsonp.js的API调用

在src的文件夹下创建api文件夹,用于储存api调用的js,新建config.js和recommend.js两个文件。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

config.js

export const commonParams = {

 g_tK: 5381,

 inCharset: 'utf-8',

 outCharset: 'utf-8',

 notice: 0,

 format: 'jsonp'

}

export const options = {

 param: 'jsonpCallback'

}

export const ERR_OK = 0

recommend.js

import jsonp from 'common/js/jsonp'

import {commonParams, options} from './config'

export function getRecommend() {

 const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg' //此处的url可以自行修改,本文是qq音乐链接

 const data = Object.assign({}, commonParams, {

 platform: 'h5',

 uin: 0,

 needNewCode: 1

 })

 return jsonp(url, data, options)

}

目录结构如下:

2.4 recommend.vue文件调用

在项目目录下的src>components>recommend>对应的文件.vue

recommend.vue

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<template>

 <div class="recommend">

  recommend

 </div>

</template>

<script type="text/ecmascript-6">

import {getRecommend} from 'api/recommend'

import {ERR_OK} from 'api/config'

export default {

 name: 'recommend',

 created() {

 this._getRecommend()

 },

 methods: {

 _getRecommend() {

  getRecommend().then((res) => {

  if (res.code === ERR_OK) {

   console.log(res.data.slider)

  }

  })

 }

 }

}

</script>

2.5 页面jsonp请求成功结果

猜你喜欢

转载自blog.csdn.net/weixin_42158115/article/details/81544298
今日推荐