vue2.0 高仿音乐webApp 跨域获取数据

最近才看了vue2.0 高仿音乐webapp 的教学视频,但是因为vue-cli(vue-cli 的版本是2.8.2) 的版本不同,自己的 /build 目录下并没有 dev-server.js 这个文件。而视频上是在这个文件里面通过调用nodejs 的接口发送请求跨域获取数据的。请问现在我用的这个版本的vue-cli 有什么方法可以替代

回答:

折腾了一天 终于搞好了,问题可能描述得不太清楚,我这里再说一遍。

如果你也看过这个视频教程,你就会知道,老师所用的方法是在 build/dev-server.js 里面开一个 express 服务器,然后它会监听到页面发送的请求,如果请求地址与这里代理的地址一样就会跳进这个代理,代码如下:

// 获取 express 对象
var app = express()
// 建立一个apiRoutes
var apiRoutes = express.Router()

apiRoutes.get('/getDiscList', function (req, res) {
  var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
  axios.get(url, {
    headers: {
      referer: 'https://c.y.qq.com/',
      host: 'c.y.qq.com'
    },
    params: req.query
  }).then((response) => {
    res.json(response.data)
  }).catch((e) => {
    console.log(e)
  })
})

apiRoutes.get('/lyric', function (req, res) {
  var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'

  axios.get(url, {
    headers: {
      referer: 'https://c.y.qq.com/',
      host: 'c.y.qq.com'
    },
    params: req.query
  }).then((response) => {
    var ret = response.data
    if (typeof ret === 'string') {
      var reg = /^\w+\(({[^()]+})\)$/
      var matches = ret.match(reg)
      if (matches) {
        ret = JSON.parse(matches[1])
      }
    }
    res.json(ret)
  }).catch((e) => {
    console.log(e)
  })
})

// express 对象占用这个url
app.use('/api', apiRoutes)

上面是vue-cli webpack 模板 1.2.4 之前的配置方法(版本可能更前)

但是以目前最新版本的vue-cli webpack 模板来说有这样的变化:
1、没有了dev-server.js 和 dev-client.js
2、package.js 里面并没有 express 和 http-proxy-middleware,我在配置的时候一直没有留意,所以一直搞到下午才算完成。

配置之前需要npm 安装 express 至于 http-proxy-middleware 视情况安装吧,不过还是有用的

然后,就像以往一样 require 一个 express

clipboard.png

最后,代码需要这样写

clipboard.png

在 devServer 里面增加一个 after方法(before 方法我没试过):

clipboard.png

参数调用 get 方法

然后就好像老师所说的那样写进去就好了

以后通过 express服务器 作为中转也可以这样做

// ————— 跟新于2018-01-03 ———————
真的很抱歉,最近的一个月都在忙着准备面试,找工作的事情没怎么留意上面的回复了 这里贴一下源码

'use strict'
require('./check-versions')()

const express = require('express')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const proxy = require('http-proxy-middleware')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const axios = require('axios')

/*
const app = express();
//欺骗域名设置 开始
var apiRoutes = express.Router()
//获取歌单列表
apiRoutes.get('/getSongList', function (req, res) {
  var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
  axios.get(url, {
    headers: {
      referer: 'https://c.y.qq.com/',
      host: 'c.y.qq.com'
    },
    params: req.query
  }).then((response) => {
    res.json(response.data)
  }).catch((e) => {
    console.log(e)
  })
})
//获取歌词
apiRoutes.get('/lyric', function (req, res) {
  var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'

  axios.get(url, {
    headers: {
      referer: 'https://c.y.qq.com/',
      host: 'c.y.qq.com'
    },
    params: req.query
  }).then((response) => {
    var ret = response.data;
    if (typeof ret === 'string') {
      var reg = /^\w+\(({[^()]+})\)$/;
      var matches = ret.match(reg);
      if (matches) {
        console.log(matches)
        ret = JSON.parse(matches[1])
      }
    }
    res.json(ret)
  }).catch((e) => {
    console.log(e)
  })
})

app.use('/api', apiRoutes);
*/

// proxy api requests
// 配置中间代理插件 其实就是获取 /config/index.js 下面的proxyTable 的键值
var proxyTable = config.dev.proxyTable;
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxy(options.filter || context, options))
})

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({sourceMap: config.dev.cssSourceMap, usePostCSS: true})
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: true,
    hot: true,
    host: process.env.HOST || config.dev.host,
    port: process.env.PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay ? {
      warnings: false,
      errors: true,
    } : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    },
    after(app) {
      app.get('/getSongList', function (req, res) {
        var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
        axios.get(url, {
          headers: {
            referer: 'https://c.y.qq.com/',
            host: 'c.y.qq.com'
          },
          params: req.query
        }).then((response) => {
          res.json(response.data)
        }).catch((e) => {
          console.log(e)
        })
      }),
      //获取歌词
      app.get('/lyric', function (req, res) {
        var url = 'http://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric.fcg'

        axios.get(url, {
          headers: {
            referer: `http://i.y.qq.com/v8/playsong.html?ADTAG=newyqq.song&songmid=${req.query.musicid}`,
            host: 'c.y.qq.com'
          },
          params: req.query
        }).then((response) => {
          var ret = response.data;
          if (typeof ret === 'string') {
            var reg = /^\w+\(({[^()]+})\)$/;
            var matches = ret.match(reg);
            if (matches) {
              ret = JSON.parse(matches[1])
            }
          }
          res.json(ret)
        }).catch((e) => {
          console.log(e)
        })
      })
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${config.dev.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
          ? utils.createNotifierCallback()
          : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

回答:

/*
    var express = require('express')
    var axios = require('axios')
    var app = express()
    var apiRoutes = express.Router()
    app.use('/api', apiRoutes)
*/


// proxy api requests
// 配置中间代理插件 其实就是获取 /config/index.js 下面的proxyTable 的键值
var axios = require('axios')
var proxyTable = config.dev.proxyTable;
Object.keys(proxyTable).forEach(function (context) {
    var options = proxyTable[context]
    if (typeof options === 'string') {
        options = { target: options }
    }
    app.use(proxy(options.filter || context, options))
})


devServer: {
        clientLogLevel: 'warning',
        historyApiFallback: true,
        hot: true,
        host: process.env.HOST || config.dev.host,
        port: process.env.PORT || config.dev.port,
        open: config.dev.autoOpenBrowser,
        overlay: config.dev.errorOverlay ? {
                warnings: false,
                errors: true,
            } : false,
        publicPath: config.dev.assetsPublicPath,
        proxy: config.dev.proxyTable,
        quiet: true, // necessary for FriendlyErrorsPlugin
        watchOptions: {
            poll: config.dev.poll,
        },
        after(app) {
            app.get('/lyric', function (req, res) {
                var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'
                axios.get(url, {
                    headers: {
                        referer: 'https://c.y.qq.com/',
                        host: 'c.y.qq.com'
                    },
                    params: req.query
                }).then((response) => {
                    var ret = response.data
                    if (typeof ret === 'string') {
                        var reg = /^\w+\(({[^()]+})\)$/
                        var matches = ret.match(reg)
                        if (matches) {
                            ret = JSON.parse(matches[1])
                        }
                    }
                    res.json(ret)
                }).catch((e) => {
                    console.log(e)
                })
            })
        }
    },

回答:

有完整的代码吗‘’

回答:

可以给个视频地址嘛~

回答:

求完整的代码,按照上面的操作还是不行啊

回答:

希望将配置部分贴出来,已纠结好久,无奈node不通,谢谢了

回答:

//首先
const express = require(‘express’)
var axios = require(‘axios’)
const app = express()
var apiRoutes = express.Router()
app.use(‘/api’, apiRoutes)

devServer: {

clientLogLevel: 'warning',
historyApiFallback: true,
hot: true,
host: process.env.HOST || config.dev.host,
port: process.env.PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay ? {
  warnings: false,
  errors: true,
} : false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
  poll: config.dev.poll,
},
after(app) {
  app.get('/api/lyric', (req, res) => {
    var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'
    axios.get(url, {
      headers: {
        referer: 'https://c.y.qq.com',
        host: 'c.y.qq.com'
      },
      params: req.query
    }).then((response) => {
      var ret = response.data
      if (typeof ret === 'string') {
        var reg = /^\w+\(({[^()]+})\)$/
        var matches = ret.match(reg)
        if (matches) {
          ret = JSON.parse(matches[1])
        }
      }
      res.json(ret)
    }).catch((e) => {
      console.log(e)
    })
  })
}

},

回答:

楼主 我也是这样写的,但是获取歌单数据的时候,中文出现了乱码,怎么解决啊

回答:

可以了,不行是因为recommed.js有问题

回答:

视频地址有吗?发一下去看看

回答:

感谢楼主,困扰了一天的问题在你这儿找到了答案. 给楼主一个棒棒哒

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注