How to implement cross-domain requests under vue-cli & how to use the after and before methods in webpack's dev-server?

1. I read the configuration instructions of webpack, but I don"t know how to use
2. This is what I tried in 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: { // 
          "/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/-sharpdevserver-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/-sharpdevelopment
        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-sharpcachebusting
        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-sharpsourcemaps)
        // 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:    */
                  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:    */
                  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. Destination address not found

clipboard.png

clipboard.png

5 afterbefore,proxy,Please help me! Thanks very much!

clipboard.png
clipboard.png


feels that all of the above are talking nonsense without using the latest vue-cli,.


404 means that the interface cannot be found. Check if there is anything wrong with the interface address


.

these configured things are really a front-end threshold. I didn't take a special look at the configuration of this piece before. I just took a brief look at

. npm run dev in

vue-cli does not start devServer, in webpack, so the before after that you configure here is certainly useless. Don't confuse the configuration of vue-cli with the configuration of webpack!

http-proxy-middleware is used in

vue-cli. For more information, please see dev-server.js. So for more information on how to use proxy, you need to see the http-proxy-middleware document: https://github.com/chimurai/h.

.
  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
      }
    }
  },

the problem of landlord has been solved. Please explain it in the answer. Thank you


the latest webpck is configured in webpack.dev.conf.js instead of dev-server. Like the landlord, I have encountered this problem. You can try to make it up.

app.use('/api', apiRoutes);
before(apiRoutes){ 
    apiRoutes.get('/api/lyric', function (req, res) {...})
}

the latest vue-cli, cross-domain, you should still use proxy to proxy, while webpack configures before and after here for webpack-dev-server to act as a server.



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) {
      // 
      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
          // json
          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)
        })
      })
    }
  },
Menu