vue引進axios插件

vue add axios css


// vue.config.js
module. exports = {
     // type :string  defalut :"/"
     // 把開發服務器架設在根路徑
     publicPath:  process. env. NODE_ENV ===  'production'
      ?  '/manage/'
      :  '/',
  
     // type :string  defalut :"dist"
     // 打包後的文件夾名字
     outputDir:  'dist',
  
     // type :string  defalut :""
     // 靜態資源目錄
     assetsDir:  'assets',
  
     // type :string  defalut :"index.html"
     // 指定生成的 index.html 的輸出路徑 (相對於 outputDir)。也能夠是一個絕對路徑。
     indexPath:  'index.html',
  
     // type :boolean  defalut :"true"
     // 生成的靜態資源在它們的文件名中包含了 hash 以便更好的控制緩存,若是是vue cli建立的index.html,則爲true,沒法使用 Vue CLI 生成的 index HTML,爲false
     filenameHashing:  true,
  
     // type :object  defalut :"undefined"
     // 設置單頁面與多頁面
     // 多頁面狀況下,每一個「page」應該有一個對應的 JavaScript 入口文件。其值應該是一個對象,對象的 key 是入口的名字,value 是:
     // 一個指定了 entry, template, filename, title 和 chunks 的對象 (除了 entry 以外都是可選的);
     // 或一個指定其 entry 的字符串。
     // 具體狀況看官網 https://cli.vuejs.org/zh/config/#pages
     // pages: {
     //   index: {
     //     // page 的入口
     //     entry: 'src/main.js',
     //     // 模板來源
     //     template: 'public/index.html',
     //     // 在 dist/index.html 的輸出
     //     filename: 'index.html',
     //     // 當使用 title 選項時,
     //     // template 中的 title 標籤須要是 <title><%= htmlWebpackPlugin.options.title %></title>
     //     title: 'Index Page',
     //     // 在這個頁面中包含的塊,默認狀況下會包含
     //     // 提取出來的通用 chunk 和 vendor chunk。
     //     chunks: ['chunk-vendors', 'chunk-common', 'index']
     //   }
     // },
  
     // type :boolean| error defalut :"true"
     // 是否在開發環境下經過 eslint-loader 在每次保存時 lint 代碼
     // true: eslint-loader 會將 lint 錯誤輸出爲編譯警告。默認狀況下,警告僅僅會被輸出到命令行,且不會使得編譯失敗,在開發和生產環境都會起做用
     // 想要在生產構建時禁用 eslint-loader  ==>  lintOnSave: process.env.NODE_ENV !== 'production'
     // false:無反應
     // error:這會強制 eslint-loader 將 lint 錯誤輸出爲編譯錯誤,同時也意味着 lint 錯誤將會致使編譯失敗。
     // 經過設置讓瀏覽器 overlay 同時顯示警告和錯誤 在 devServe 配置項中  ==>  overlay: {warnings: true,errors: true}
     lintOnSave:  true,
  
     // type :boolean defalut :"false"
     // 是否使用包含運行時編譯器的 Vue 構建版本。設置爲 true 後你就能夠在 Vue 組件中使用 template 選項了,可是這會讓你的應用額外增長 10kb 左右。
     // 具體信息看官網 https://cn.vuejs.org/v2/guide/installation.html#運行時+編譯器vs.只包含運行時
     runtimeCompiler:  false,
  
     // type :Array<string | RegExp> defalut :"[]" (RegExp) ==> 正則
     // 默認狀況下 babel-loader 會忽略全部 node_modules 中的文件。若是你想要經過 Babel 顯式轉譯一個依賴,能夠在這個選項中列出來
     transpileDependencies: [],
  
     // type :boolean  defalut :"true"
     // SourceMap 一個存儲源代碼與編譯代碼對應位置映射的信息文件
     // 若是你不須要生產環境的 source map,能夠將其設置爲 false 以加速生產環境構建
     productionSourceMap:  true,
  
     // type :String  defalut : undefined
     // 設置生成的 HTML 中 <link rel="stylesheet"> 和 <script> 標籤的 crossorigin 屬性。須要注意的是該選項僅影響由 html-webpack-plugin 在構建時注入的標籤 - 直接寫在模版 (public/index.html) 中的標籤不受影響。
     // 這個應該和標籤跨域有關  具體細節看  ==> https://developer.mozilla.org/zh-CN/docs/Web/HTML/CORS_settings_attributes
     // crossorigin: '',
  
     // type :boolean  defalut :"false"
     // 在生成的 HTML 中的 <link rel="stylesheet"> 和 <script> 標籤上啓用 Subresource Integrity (SRI)。若是你構建後的文件是部署在 CDN 上的,啓用該選項能夠提供額外的安全性。
     // 須要注意的是該選項僅影響由 html-webpack-plugin 在構建時注入的標籤 - 直接寫在模版 (public/index.html) 中的標籤不受影響。
     // 另外,當啓用 SRI 時,preload resource hints 會被禁用,由於 Chrome 的一個 bug 會致使文件被下載兩次
     // SRI(子資源完整性) https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
     integrity:  false,
  
     // type: object | function
     // 調整 webpack 配置
     // 若是這個值是一個對象,則會經過 webpack-merge 合併到最終的配置中。
     // 若是這個值是一個函數,則會接收被解析的配置做爲參數。該函數及能夠修改配置並不返回任何東西,也能夠返回一個被克隆或合併過的配置版本。
     // 細節查看 https://cli.vuejs.org/zh/guide/webpack.html#簡單的配置方式
     configureWebpack :  config  => {
       if ( process. env. NODE_ENV ===  'production') {
         // 爲生產環境修改配置...
      }  else {
         // 爲開發環境修改配置...
      }
    },
  
     // type:function
     // 是一個函數,會接收一個基於 webpack-chain 的 ChainableConfig 實例。容許對內部的 webpack 配置進行更細粒度的修改。
     // 具體細節查看 https://cli.vuejs.org/zh/guide/webpack.html#鏈式操做(高級)
     // 你須要熟悉 webpack-chain 的 API 並閱讀一些源碼以便了解如何最大程度利用好這個選項,可是比起直接修改 webpack 配置,它的表達能力更強,也更爲安全。
     // chainWebpack   ==>  我有點理解不了,應該是修改 添加 替換loader
  
     css: {
       // type :boolean  defalut :"false"
       // 默認狀況下,只有 *.module.[ext] 結尾的文件纔會被視做 CSS Modules 模塊。設置爲 true 後你就能夠去掉文件名中的 .module 並將全部的 *.(css|scss|sass|less|styl(us)?) 文件視爲 CSS Modules 模塊。
       // 細節查看https://cli.vuejs.org/zh/guide/css.html#css-modules
       modules:  false,
  
       // type:boolean | object defalut:生產環境下是 true,開發環境下是 false
       // 是否將組件中的 CSS 提取至一個獨立的 CSS 文件中 (而不是動態注入到 JavaScript 中的 inline 代碼)。
       // 看成爲一個庫構建時,你也能夠將其設置爲 false 省得用戶本身導入 CSS
       // 提取 CSS 在開發環境模式下是默認不開啓的,由於它和 CSS 熱重載不兼容。然而,你仍然能夠將這個值顯性地設置爲 true 在全部狀況下都強制提取。
       // extract
  
       // type:boolean defalut :"false"
       // 是否爲 CSS 開啓 source map。設置爲 true 以後可能會影響構建的性能。
       sourceMap:  false,
  
       // type:object defalut:{}
       // 向 CSS 相關的 loader 傳遞選項。css預設器配置項
       // loader 能夠經過 loaderOptions 配置,包括:css-loader postcss-loader sass-loader less-loader stylus-loader
       // 具體細節查看 https://cli.vuejs.org/zh/guide/css.html#向預處理器Loader傳遞選項
       loaderOptions: {
         css: {
           // 這裏的選項會傳遞給 css-loader
        },
         postcss: {
           // 這裏的選項會傳遞給 postcss-loader
        }
      }
    },
     // type:boolean defalut:require('os').cpus().length > 1
     // 是否爲 Babel 或 TypeScript 使用 thread-loader。該選項在系統的 CPU 有多於一個內核時自動啓用,僅做用於生產構建
     // 構建時開啓多進程處理babel編譯
     parallel:  require( 'os'). cpus(). length >  1,
  
     // type: object
     // 單頁插件相關配置  向PWA插件傳遞選項
     // 具體細節 https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
     pwa: {},
  
     // type:object
     // 這是一個不進行任何 schema 驗證的對象,所以它能夠用來傳遞任何第三方插件選項。
     // schema數據庫對象的集合 (也有其餘意思。。。)
     pluginOptions: {},
  
     // dev: {
     //   proxyTable: {
     //     '/apis': {
     //       // 測試環境
     //       target: 'http://localhost:9000', // 接口域名
     //       changeOrigin: true, // 是否跨域
     //       pathRewrite: {
     //         '^/apis': '' // 須要rewrite重寫的,
     //       }
     //     }
     //   }
     // },
  
     // type:object
     // 開發配置
     // 細節查看 https://webpack.js.org/configuration/dev-server/#devserver
     // disableHostCheck: true,
     devServer: {
       open:  true,
       hot:  true,
       host:  '0.0.0.0',
       port:  '8083',
       disableHostCheck:  true,
       proxy: {
         '/api' : {
           target:  process. env. NODE_ENV ===  'production' ?  'http://127.0.0.1:9000' :  'http://172.17.10.175:9000',
           // 在本地會建立一個虛擬服務端,而後發送請求的數據,並同時接收請求的數據,這樣服務端和服務端進行數據的交互就不會有跨域問題
           changeOrigin:  true,
           ws:  true,
           pathRewrite: {
             // 替換target中的請求地址,也就是說之後你在請求http://api.jisuapi.com/XXXXX這個地址的時候直接寫成/api便可
             '^/api' :  '/'
          }
        }
      }
    }
  }
  
pasting

 pastinghtml

'use strict'

import  Vue  from  'vue'
import  axios  from  'axios'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// let config = {
//   // baseURL: process.env.baseURL || process.env.apiUrl || ""
//   timeout: 60 * 1000, // Timeout
//   withCredentials: true, // Check cross-site Access-Control
//   headers: {
//     'Content-Type': 'application/x-www-form-urlencoded',
//     'Access-Control-Allow-Origin': 'http://localhost:8080'
//   }
// }
//
// const _axios = axios.create(config)
// // axios.defaults.withCredentials = true
// // axios.defaults.crossDomain = true
// // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.interceptors.request.use(
//   function (config) {
//     // Do something before request is sent
//     // config.headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': 'http://localhost:8080' }
//     return config
//   },
//   function (error) {
//     // Do something with request error
//     return Promise.reject(error)
//   }
// )
//
// // Add a response interceptor
// _axios.interceptors.response.use(
//   function (response) {
//     // Do something with response data
//     return response
//   },
//   function (error) {
//     // Do something with response error
//     return Promise.reject(error)
//   }
// )
//
// Plugin.install = function (Vue, options) {
//   Vue.axios = _axios
//   window.axios = _axios
//   Object.defineProperties(Vue.prototype, {
//     axios: {
//       get () {
//         return _axios
//       }
//     },
//     $axios: {
//       get () {
//         return _axios
//       }
//     }
//   })
// }
// /**
//  * 封裝get方法
//  * @param url
//  * @param data
//  * @returns {Promise}
//  */
//
// export function fetch (url, params = {}) {
//   return new Promise((resolve, reject) => {
//     axios.get(url, {
//       params: params
//     })
//       .then(response => {
//         resolve(response.data)
//       })
//       .catch(err => {
//         reject(err)
//       })
//   })
// }

// /**
//  * 封裝post請求
//  * @param url
//  * @param data
//  * @returns {Promise}
//  */
//
// export function post (url, data = {}) {
//   return new Promise((resolve, reject) => {
//     axios.post(url, data)
//       .then(response => {
//         resolve(response.data)
//       }, err => {
//         reject(err)
//       })
//   })
// }
//
// /**
//  * 封裝patch請求
//  * @param url
//  * @param data
//  * @returns {Promise}
//  */
//
// export function patch (url, data = {}) {
//   return new Promise((resolve, reject) => {
//     axios.patch(url, data)
//       .then(response => {
//         resolve(response.data)
//       }, err => {
//         reject(err)
//       })
//   })
// }
//
// /**
//  * 封裝put請求
//  * @param url
//  * @param data
//  * @returns {Promise}
//  */
//
// export function put (url, data = {}) {
//   return new Promise((resolve, reject) => {
//     axios.put(url, data)
//       .then(response => {
//         resolve(response.data)
//       }, err => {
//         reject(err)
//       })
//   })
// }
// Vue.use(Plugin)
//
// export default Plugin

let  service =  axios. create({
   // headers: {'Content-Type': 'application/json'},
   timeout:  60000
})

// 設置 post、put 默認 Content-Type
service. defaults. headers. get[ 'Content-Type'] =  'application/json'
service. defaults. headers. get[ 'Access-Control-Allow-Origin'] =  '*'
service. defaults. headers. post[ 'Content-Type'] =  'application/json'
service. defaults. headers. post[ 'Access-Control-Allow-Origin'] =  '*'
service. defaults. headers. put[ 'Content-Type'] =  'application/json'

// 添加請求攔截器
service. interceptors. request. use(
  ( config=> {
     if ( config. method ===  'post' ||  config. method ===  'put') {
       // post、put 提交時,將對象轉換爲string, 爲處理Java後臺解析問題
       if ( config. headers[ 'Content-Type'] ===  'application/json') {
         config. data =  JSON. stringify( config. data)
      }
    }
     // 請求發送前進行處理
     return  config
  },
  ( error=> {
     // 請求錯誤處理
     return  Promise. reject( error)
  }
)

// 添加響應攔截器
service. interceptors. response. use(
)

/**
 * 建立統一封裝過的 axios 實例
 *  @return   {AxiosInstance}
 */
export  default  service 
相關文章
相關標籤/搜索