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 
相关文章
相关标签/搜索