1. 程式人生 > >vue開發中的跨域處理

vue開發中的跨域處理

前端開發中的跨域處理方式有很多,jsonp、服務端配置、nginx代理等等。本文中這些都不涉及,這裡主要記錄下載vue開發中遇到的跨域問題,以及在使用webpack代理處理跨域遇到的一些問題。

vue開發中遇到跨域問題,最簡單的解決方式就是使用webpack代理(proxyTable)將介面代理到本地。

專案的原始配置如下(檔案目錄 config/index.js):

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

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    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: 'cheap-module-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,

    cssSourceMap: true
  }
}

這裡可以看到有個proxyTable配置項,我們可以在這裡配置要代理的介面地址,如下:

proxyTable: {
  '/api': {
     target: 'https://baidu.com',
     changeOrigin: true,
     pathRewrite: {
        '/api': ''
     }
   }
}

關於怎麼配置就不用多說了,網上隨便一搜就有一大堆。我主要是想介紹一下各個配置項的意義,以及我當時在理解這些配置是遇到的誤區。

'/api'表示的是代理後的地址,target表示的是要代理的地址

在上面的配置就是將https://baidu.com 代理到 /api,也就是說,你本來的介面地址是https://baidu.com/v1/home,配置後的請求地址就變成了 本地ur/api/v1/home。

changeOrigin: true表示介面需要跨域

開始最讓我迷惑的就是這個pathRewrite配置。上面的配置表示的意思是將https://baidu.com代理到了/api,然後你本地的請求變成了xxxxx/api/v1/home,這是你在network中可以看到的介面請求地址,但是實際上伺服器的介面地址是沒有'api'。所以這個時候就需要用pathRewrite將'api'去掉,這時請求伺服器的實際地址就是https://baidu.com/v1/home。但是你本地的network中的請求地址還是xxxx/api/v1/home,看到這裡的時候就不要糾結了,通過代理後傳送的請求地址其實是正確的(開始在這裡糾結了好久)。

假如說你的介面地址本來就是https://baidu.com/api/v1/home,那麼pathRewrite這個配置你也就可以不寫啦。

或許你會問,既然多個'api',那我在代理的時候直接把配置改成 '/': { }不就行了,不加api不就ok了。瞧瞧告訴你,是不行的,至於為什麼不行,我還沒深究,如果你知道請告訴我。

最後在釋出上線的時候可以用nginx將api後面的介面重定向到伺服器的介面地址。參考