如何将Vue二次封装axios流程改写为高效的长尾关键词?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1306个文字,预计阅读时间需要6分钟。
目录
一、为什么要封装axios
二、怎么封装axios
三、具体步骤
四、Vue项目的初期配置
五、配置config文件中的代理地址
六、封装axios实例-request.js
七、封装请求-http.js
八、正式封装API用于发送请求-ap.js
目录
- 一、为什么要封装axios
- 二、怎么封装axios
- 三、具体步骤
- vue项目的前期配置
- 配置config文件中的代理地址
- 封装axios实例-request.js
- 四、封装请求-vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/': {
target: 'localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
},
'/ws/*': {
target: 'ws://127.0.0.1:8080',
ws: true
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8082, // 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, // 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
*/
// 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
// vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
封装axios实例-request.js
/**** request.js ****/ // 导入axios import axios from 'axios' // 使用element-ui Message做消息提醒 import { Message} from 'element-ui'; //1. 创建新的axios实例, const service = axios.create({ // 公共接口--这里注意后面会讲 baseURL: process.env.BASE_API, // 超时时间 单位是ms,这里设置了3s的超时时间 timeout: 3 * 1000 }) // 2.请求拦截器 service.interceptors.request.use(config => { //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加 config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换 config.headers = { 'Content-Type':'application/json' //配置请求头 } //如有需要:注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie //const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下 //if(token){ //config.params = {'token':token} //如果要求携带在参数中 //config.headers.token= token; //如果要求携带在请求头中 //} return config }, error => { Promise.reject(error) }) // 3.响应拦截器 service.interceptors.response.use(response => { //接收到响应数据并成功后的一些共有的处理,关闭loading等 return response }, error => { /***** 接收到异常响应的处理开始 *****/ if (error && error.response) { // 1.公共错误处理 // 2.根据响应码具体处理 switch (error.response.status) { case 400: error.message = '错误请求' break; case 401: error.message = '未授权,请重新登录' break; case 403: error.message = '拒绝访问' break; case 404: error.message = '请求错误,未找到该资源' window.location.href = "/NotFound" break; case 405: error.message = '请求方法未允许' break; case 408: error.message = '请求超时' break; case 500: error.message = '服务器端出错' break; case 501: error.message = '网络未实现' break; case 502: error.message = '网络错误' break; case 503: error.message = '服务不可用' break; case 504: error.message = '网络超时' break; case 505: error.message = 'http版本不支持该请求' break; default: error.message = `连接错误${error.response.status}` } } else { // 超时处理 if (JSON.stringify(error).includes('timeout')) { Message.error('服务器响应超时,请刷新当前页') } error.message = '连接服务器失败' } Message.error(error.message) /***** 处理结束 *****/ //如果不需要错误处理,以上的处理过程都可省略 return Promise.resolve(error.response) }) //4.导入文件 export default service
四、封装请求-http.js
/**** http.js ****/ // 导入封装好的axios实例 import request from './request' const http ={ /** * methods: 请求 * @param url 请求地址 * @param params 请求参数 */ get(url,params){ const config = { method: 'get', url:url } if(params) config.params = params return request(config) }, post(url,params){ const config = { method: 'post', url:url } if(params) config.data = params return request(config) }, put(url,params){ const config = { method: 'put', url:url } if(params) config.params = params return request(config) }, delete(url,params){ const config = { method: 'delete', url:url } if(params) config.params = params return request(config) } } //导出 export default http
五、正式封装API用于发送请求-api.js
import request from "@/utils/request.js"; import qs from "qs"; const baseUrl = '/api/jwt/auth' //登录 export function authCodeLogin(params) { return request({ url: baseUrl + "/authCodeLogin/" + params.code, method: "get", }); } //退出 export function authLogout(params) { return request({ url: baseUrl + "/logout", method: "get", }); } //获取用户数据 export function getUserInfo(params) { return request({ url: baseUrl + "/getUserInfo", method: "get", params:qs.stringfy(params) }); } //其实,也不一定就是params,也可以是 query 还有 data 的呀! //params是添加到url的请求字符串中的,用于get请求。会将参数加到 url后面。所以,传递的都是字符串。无法传递参数中含有json格式的数据 //而data是添加到请求体(body)中的, 用于post请求。添加到请求体(body)中,json 格式也是可以的。
六、如何在vue文件中调用
用到哪个api 就调用哪个接口
import { authCodeLogin } from '@/api/api.js' getModellogin(code){ let params = { code: code, } authCodeLogin(params).then(res=>{ if (res.code === 200) { localStorage.clear() // 菜单 this.$store.dispatch('saveMenu', []) // this.getFloorMenu() // this.getmenu() this.$router.push('/') }else{ console.log('error'); } }) },
到此这篇关于Vue二次封装axios流程详解的文章就介绍到这了,更多相关Vue封装axios内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!
本文共计1306个文字,预计阅读时间需要6分钟。
目录
一、为什么要封装axios
二、怎么封装axios
三、具体步骤
四、Vue项目的初期配置
五、配置config文件中的代理地址
六、封装axios实例-request.js
七、封装请求-http.js
八、正式封装API用于发送请求-ap.js
目录
- 一、为什么要封装axios
- 二、怎么封装axios
- 三、具体步骤
- vue项目的前期配置
- 配置config文件中的代理地址
- 封装axios实例-request.js
- 四、封装请求-vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/': {
target: 'localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
},
'/ws/*': {
target: 'ws://127.0.0.1:8080',
ws: true
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8082, // 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, // 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
*/
// 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
// vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
封装axios实例-request.js
/**** request.js ****/ // 导入axios import axios from 'axios' // 使用element-ui Message做消息提醒 import { Message} from 'element-ui'; //1. 创建新的axios实例, const service = axios.create({ // 公共接口--这里注意后面会讲 baseURL: process.env.BASE_API, // 超时时间 单位是ms,这里设置了3s的超时时间 timeout: 3 * 1000 }) // 2.请求拦截器 service.interceptors.request.use(config => { //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加 config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换 config.headers = { 'Content-Type':'application/json' //配置请求头 } //如有需要:注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie //const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下 //if(token){ //config.params = {'token':token} //如果要求携带在参数中 //config.headers.token= token; //如果要求携带在请求头中 //} return config }, error => { Promise.reject(error) }) // 3.响应拦截器 service.interceptors.response.use(response => { //接收到响应数据并成功后的一些共有的处理,关闭loading等 return response }, error => { /***** 接收到异常响应的处理开始 *****/ if (error && error.response) { // 1.公共错误处理 // 2.根据响应码具体处理 switch (error.response.status) { case 400: error.message = '错误请求' break; case 401: error.message = '未授权,请重新登录' break; case 403: error.message = '拒绝访问' break; case 404: error.message = '请求错误,未找到该资源' window.location.href = "/NotFound" break; case 405: error.message = '请求方法未允许' break; case 408: error.message = '请求超时' break; case 500: error.message = '服务器端出错' break; case 501: error.message = '网络未实现' break; case 502: error.message = '网络错误' break; case 503: error.message = '服务不可用' break; case 504: error.message = '网络超时' break; case 505: error.message = 'http版本不支持该请求' break; default: error.message = `连接错误${error.response.status}` } } else { // 超时处理 if (JSON.stringify(error).includes('timeout')) { Message.error('服务器响应超时,请刷新当前页') } error.message = '连接服务器失败' } Message.error(error.message) /***** 处理结束 *****/ //如果不需要错误处理,以上的处理过程都可省略 return Promise.resolve(error.response) }) //4.导入文件 export default service
四、封装请求-http.js
/**** http.js ****/ // 导入封装好的axios实例 import request from './request' const http ={ /** * methods: 请求 * @param url 请求地址 * @param params 请求参数 */ get(url,params){ const config = { method: 'get', url:url } if(params) config.params = params return request(config) }, post(url,params){ const config = { method: 'post', url:url } if(params) config.data = params return request(config) }, put(url,params){ const config = { method: 'put', url:url } if(params) config.params = params return request(config) }, delete(url,params){ const config = { method: 'delete', url:url } if(params) config.params = params return request(config) } } //导出 export default http
五、正式封装API用于发送请求-api.js
import request from "@/utils/request.js"; import qs from "qs"; const baseUrl = '/api/jwt/auth' //登录 export function authCodeLogin(params) { return request({ url: baseUrl + "/authCodeLogin/" + params.code, method: "get", }); } //退出 export function authLogout(params) { return request({ url: baseUrl + "/logout", method: "get", }); } //获取用户数据 export function getUserInfo(params) { return request({ url: baseUrl + "/getUserInfo", method: "get", params:qs.stringfy(params) }); } //其实,也不一定就是params,也可以是 query 还有 data 的呀! //params是添加到url的请求字符串中的,用于get请求。会将参数加到 url后面。所以,传递的都是字符串。无法传递参数中含有json格式的数据 //而data是添加到请求体(body)中的, 用于post请求。添加到请求体(body)中,json 格式也是可以的。
六、如何在vue文件中调用
用到哪个api 就调用哪个接口
import { authCodeLogin } from '@/api/api.js' getModellogin(code){ let params = { code: code, } authCodeLogin(params).then(res=>{ if (res.code === 200) { localStorage.clear() // 菜单 this.$store.dispatch('saveMenu', []) // this.getFloorMenu() // this.getmenu() this.$router.push('/') }else{ console.log('error'); } }) },
到此这篇关于Vue二次封装axios流程详解的文章就介绍到这了,更多相关Vue封装axios内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!

