鍍金池/ 問答/HTML5  HTML/ 怎么在 vue-cli下面實(shí)現(xiàn)跨域請(qǐng)求&&webpack 的 d

怎么在 vue-cli下面實(shí)現(xiàn)跨域請(qǐng)求&&webpack 的 dev-server 里面的after和before方法怎么使用?

1、看了webpack 的配置說明,但是不知道怎么使用
2、這是我在index里面做的嘗試,

'use strict'
// Template version: 1.2.3
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')
var express = require('express')
var app = express()
var axios = require('axios')
var apiRoutes = express.Router()

    module.exports = {
      dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: { //跨域。。。代理服務(wù) 
          '/api': {
                    target: 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg',
                changeOrigin: true,
                pathRewrite: {
                 '^/api': ''
                }
          }
        },
        // Various Dev Server settings
        host: 'localhost', // can be overwritten by process.env.HOST
        port: 8085, // can be overwritten by process.env.HOST, if port is in use, a free one will be determined
        autoOpenBrowser: true,
        errorOverlay: true,
        notifyOnErrors: true,
        poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    
        // Use Eslint Loader?
        // If true, your code will be linted during bundling and
        // linting errors and warnings will be shown in the console.
        useEslint: true,
        // If true, eslint errors and warnings will also be shown in the error overlay
        // in the browser.
        showEslintErrorsInOverlay: false,
    
        /**
         * Source Maps
         */
    
        // https://webpack.js.org/configuration/devtool/#development
        devtool: 'eval-source-map',
    
        // If you have problems debugging vue-files in devtools,
        // set this to false - it *may* help
        // https://vue-loader.vuejs.org/en/options.html#cachebusting
        cacheBusting: true,
    
        // CSS Sourcemaps off by default because relative paths are "buggy"
        // with this option, according to the CSS-Loader README
        // (https://github.com/webpack/css-loader#sourcemaps)
        // In our experience, they generally work as expected,
        // just be aware of this issue when enabling this option.
        cssSourceMap: false,
        before(apiRoutes) {
          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') {
                    /* \w:字母、數(shù)字、下劃線   中間就是以大括號(hào)開始,小括號(hào)結(jié)束且不為( 、)的字符,一個(gè)和多個(gè)*/
                  var reg = /^\w+\(({[^()]+})\)$/ /*==> MusicJsonCallback({\"retcode\":0,\"code\":0,\"subcode\...."})*/
                  var matches = ret.match(reg)
                  if (matches) {
                    ret = JSON.parse(matches[1])
                  }
                }
                res.json(ret)
              }).catch((e) => {
                console.log(e)
              })
            })
        },
        after(apiRoutes){
          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') {
                    /* \w:字母、數(shù)字、下劃線   中間就是以大括號(hào)開始,小括號(hào)結(jié)束且不為( 、)的字符,一個(gè)和多個(gè)*/
                  var reg = /^\w+\(({[^()]+})\)$/ /*==> MusicJsonCallback({\"retcode\":0,\"code\":0,\"subcode\...."})*/
                  var matches = ret.match(reg)
                  if (matches) {
                    ret = JSON.parse(matches[1])
                  }
                }
                res.json(ret)
                console.log(res.json(ret))
              }).catch((e) => {
                console.log(e)
              })
            })
        }
      },

3、

    export function getLyric(mid) {
    
      const url = '/api/lyric'
    
      const data = Object.assign({}, commonParams, {
          g_tk: 5381,
        songmid: mid,
        platform: 'yqq',
        hostUin: 0,
        needNewCode: 0,
        categoryId: 10000000,
        pcachetime: +new Date(),
        format: 'json'
      })
    
      return axios.get(url, {
        params: data
      }).then((res) => {
        return Promise.resolve(res.data)
      })
    }

4、找不到目標(biāo)地址

clipboard.png

clipboard.png

5、 下面的after和before方法,不知道怎么用,起作用的就只是proxy,Please help me! Thanks very much!

clipboard.png
clipboard.png

回答
編輯回答
純妹

404 是指找不到接口,你看下接口地址有么有錯(cuò)

2017年7月24日 05:54
編輯回答
怪痞

圖片描述

2017年1月14日 10:54
編輯回答
怣痛

devServer: {

clientLogLevel: 'warning',
historyApiFallback: {
  rewrites: [
    { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
  ],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: 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,
},
/**
 * axios
 */
before(app) {
  // 獲取推薦頁(yè)面列表
  app.get('/api/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)
    })
  })
  // 獲取歌詞
  app.get('/api/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
      // 字符串轉(zhuǎn)換成json對(duì)象
      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)
    })
  })
}

},

2017年10月4日 20:30
編輯回答
絯孑氣

感覺上面的全部都沒有用最新的vue-cli,就瞎說

2017年12月26日 04:53
編輯回答
鹿惑

最新的vue-cli,跨域,你應(yīng)該使用的依然是proxy去進(jìn)行代理,而webpack配置這里的before和after是為了讓webpack-dev-server充當(dāng)服務(wù)器端使用的。圖片描述

2018年8月26日 16:15
編輯回答
掛念你

最新的webpck用的不是dev-server而是全部在webpack.dev.conf.js里面進(jìn)行配置,我和樓主一樣碰到過這個(gè)問題,樓主可以補(bǔ)全下試試看:

app.use('/api', apiRoutes);
before(apiRoutes){ 
    apiRoutes.get('/api/lyric', function (req, res) {...})
}
2017年6月21日 22:55
編輯回答
逗婦惱

樓主問題解決了麻煩在答案中說明一下,謝謝了

2017年6月11日 14:52
編輯回答
熟稔

這些配置的東西真的算是個(gè)前端的門檻了... 之前沒有怎么特意看這塊的配置,剛才簡(jiǎn)單看了下

vue-cli 中 npm run dev 啟動(dòng)的不是 webpack 中的 devServer,所以你這里配置的 before after 肯定沒有用。不要混淆了 vue-cli 的配置和 webpack 的配置!

vue-cli 中用的是 http-proxy-middleware,詳見 dev-server.js。因此具體 proxy 怎么用,需要看http-proxy-middleware 的文檔:https://github.com/chimurai/h...

2018年4月24日 08:13
編輯回答
離魂曲
  devServer: {
    historyApiFallback: true,
    stats: 'minimal',
    noInfo: false,
    compress: true,
    host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true,
    proxy: {
      '*': {
        target: 'http://192.168.1.202',
        changeOrigin: true,
        secure: false
      }
    }
  },
2017年8月8日 09:22