zoukankan      html  css  js  c++  java
  • 浏览器能正常访问的url,superagent不能正常访问

    在写音乐播放器的过程中,我需要获取qq音乐排行榜的信息,于是我向以前一样,在后台的MusicController中添加一个getTopList方法
    然后写下以下代码

    // 获取排行
      async getTopList(ctx) {
        const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg'
        const data = Object.assign({}, commonParams, {
          g_tk: 5381,
          uin: 0,
          format: 'json',
          notice: 0,
          platform: 'h5',
          needNewCode: 1,
          _: 1533213793328
        })
        ctx.body = await request.get(url)
          .query(data)
          .then(res => {
            return res.text
          })
      }
    

    然后使用postman来测试我的接口
    神奇的事情发生了,204 no content。。。
    我试着打印了一下发现res.text是undefine
    于是我又考虑是不是referer的原因,添加了以下两行代码

    .set('referer', 'https://y.qq.com/m/index.html')
    .set('host', 'c.y.qq.com')
    

    结果还是undefine
    这下我没办法了,开始了面向google编程
    最后在superagent仓库中的issue中找到了解答
    原来当mime的type是x-javascript时,superagent获取数据没有缓冲,需要添加buffer(true)才能获取到,

     ctx.body = await request.get(url)
          .query(data)
          .set('referer', 'https://y.qq.com/m/index.html')
          .set('host', 'c.y.qq.com')
          .buffer(true)
          .then(res => {
            return res.text
          })
    

    这样我就获取到了正确的数据
    接下来我就开始搜索x-javascript到底是何方神圣 ,在stackoverflow上看到了这篇文章
    原来application/x-javascripttext/javascriptapplication/javascript的一个过渡,而且x-javascript是实验性的,请不要使用他

  • 相关阅读:
    logback-spring.xml配置文件详解
    SpringBoot-Controller接收参数的几种常用方式
    spring boot配置定时任务设置
    SpringCloud 配置文件 application.yml和 bootstrap.yml区别
    ajax/get请求
    ajax封装2
    ajax封装1
    楼层特效
    旋转动画
    联动动画
  • 原文地址:https://www.cnblogs.com/swust-wangyf/p/9410544.html
Copyright © 2011-2022 走看看