天天看點

Vue-devServer.proxy代理配置

1、基本用法

// vue.config.js
devServer: {
  proxy: {
    '/api': {
      target: 'http://localhost:81',
    }
  }
}

// vue/src/api/index.js
import http from './httpInstance'
const prefix = process.env.NODE_ENV === 'development' ? '/api' : '/api'
const getList = data => {
  return http({
    method: 'post',
    url: prefix + '/getList',
    data
  })
}
           

        現在,請求到 /api/xxx 現在會被代理到請求http://localhost:81/api/xxx,例如 /api/getList現在會被代理到請求 http://localhost:81/api/getList。

2、忽略API字首

        如果不希望傳遞/api,則需要重寫路徑:

devServer: {
  proxy: {
    '/api': {
      target: 'http://localhost:81',
      pathRewrite: { '^/api': '' },
    }
  }
}
           

        現在,請求到 /api/xxx 現在會被代理到請求 http://localhost:81/xxx, 例如 /api/getList 現在會被代理到請求 http://localhost:81/getList。

3、代理多個路徑

        如果想将多個特定路徑代理到同一目标,則可以使用一個或多個帶有context屬性的對象的數組:

devServer: {
  proxy: [{
    context: ['/auth', '/api'],
    target: 'http://localhost:81',
  }]
}
           

4、忽略https安全提示

        預設情況下,不接受運作在https上,且使用了無效證書的後端伺服器。如果你想要接受,隻要設定 secure: false 就行。修改配置如下:

devServer: {
  proxy: {
    '/api': {
      target: 'http://localhost:81',
      secure: false,
    }
  }
}
           

5、解決跨域原理

        預設情況下,代理時會保留主機頭的來源,可以将changeOrigin設定為true以覆寫此行為:

devServer: {
  proxy: {
    '/api': {
      target: 'http://localhost:81',
      changeOrigin: true,
    }
  }
}
           

6、自定義規則

        有時如果不想代理所有的請求。可以基于一個函數的傳回值繞過代理。 在函數中可以通路請求體、響應體和代理選項。必須傳回 false 或路徑,來跳過代理請求。 例如:對于浏覽器請求,你想要提供一個 HTML 頁面,但是對于 API 請求則保持代理。你可以這樣做:

devServer: {
  proxy: {
    '/api': {
      target: 'http://localhost:81',
      bypass: function (req, res, proxyOptions) {
        if (req.headers.accept.indexOf('html') !== -1) {
          return '/index.html';
        }
      },
    }
  }
}
           

7、更多參數

target:"xxx",            // 要使用url子產品解析的url字元串
forward:"xxx",           // 要使用url子產品解析的url字元串
agent:{},                // 要傳遞給http(s).request的對象
ssl:{},                  // 要傳遞給https.createServer()的對象
ws:true/false,           // 是否代理websockets
xfwd:true/false,         // 添加x-forward标頭
secure:true/false,       // 是否驗證SSL Certs
toProxy:true/false,      // 傳遞絕對URL作為路徑(對代理代理很有用)
prependPath:true/false,  // 預設值:true 指定是否要将目标的路徑添加到代理路徑
ignorePath:true/false,   // 預設值:false 指定是否要忽略傳入請求的代理路徑
localAddress:"xxx",      // 要為傳出連接配接綁定的本地接口字元串
changeOrigin:true/false, // 預設值:false 将主機标頭的原點更改為目标URL