鍍金池/ 問答/HTML/ vue2.0 高仿音樂webApp 跨域獲取數(shù)據(jù)

vue2.0 高仿音樂webApp 跨域獲取數(shù)據(jù)

最近才看了vue2.0 高仿音樂webapp 的教學(xué)視頻,但是因?yàn)関ue-cli(vue-cli 的版本是2.8.2) 的版本不同,自己的 /build 目錄下并沒有 dev-server.js 這個(gè)文件。而視頻上是在這個(gè)文件里面通過調(diào)用nodejs 的接口發(fā)送請求跨域獲取數(shù)據(jù)的。請問現(xiàn)在我用的這個(gè)版本的vue-cli 有什么方法可以替代

回答
編輯回答
悶油瓶

//首先
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)
    })
  })
}

},

2018年2月20日 05:54
編輯回答
情皺

可以了,不行是因?yàn)閞ecommed.js有問題

2018年3月4日 04:42
編輯回答
陌離殤

可以給個(gè)視頻地址嘛~

2017年2月17日 09:19
編輯回答
九年囚

希望將配置部分貼出來,已糾結(jié)好久,無奈node不通,謝謝了

2018年3月7日 10:06
編輯回答
舊螢火

感謝樓主,困擾了一天的問題在你這兒找到了答案. 給樓主一個(gè)棒棒噠

2018年7月24日 23:48
編輯回答
檸檬藍(lán)

折騰了一天 終于搞好了,問題可能描述得不太清楚,我這里再說一遍。

如果你也看過這個(gè)視頻教程,你就會知道,老師所用的方法是在 build/dev-server.js 里面開一個(gè) express 服務(wù)器,然后它會監(jiān)聽到頁面發(fā)送的請求,如果請求地址與這里代理的地址一樣就會跳進(jìn)這個(gè)代理,代碼如下:

// 獲取 express 對象
var app = express()
// 建立一個(gè)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 對象占用這個(gè)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,我在配置的時(shí)候一直沒有留意,所以一直搞到下午才算完成。

配置之前需要npm 安裝 express 至于 http-proxy-middleware 視情況安裝吧,不過還是有用的

然后,就像以往一樣 require 一個(gè) express

clipboard.png

最后,代碼需要這樣寫

clipboard.png

在 devServer 里面增加一個(gè) after方法(before 方法我沒試過):

clipboard.png

參數(shù)調(diào)用 get 方法

然后就好像老師所說的那樣寫進(jìn)去就好了

以后通過 express服務(wù)器 作為中轉(zhuǎn)也可以這樣做

// --------------- 跟新于2018-01-03 ---------------------
真的很抱歉,最近的一個(gè)月都在忙著準(zhǔn)備面試,找工作的事情沒怎么留意上面的回復(fù)了 這里貼一下源碼

'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();
//欺騙域名設(shè)置 開始
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
// 配置中間代理插件 其實(shí)就是獲取 /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)
    }
  })
})
2017年5月30日 05:26
編輯回答
孤星

有完整的代碼嗎‘’

2018年2月4日 09:25
編輯回答
祉小皓

樓主 我也是這樣寫的,但是獲取歌單數(shù)據(jù)的時(shí)候,中文出現(xiàn)了亂碼,怎么解決啊

2018年9月2日 05:08
編輯回答
安若晴

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

2017年7月4日 16:32
編輯回答
做不到

視頻地址有嗎?發(fā)一下去看看

2017年11月21日 03:19