Vue项目中的http请求统一管理
module.exports = {
dev: {
// Paths
assetsSubDirectory: '/',
assetsPublicPath: '/',
proxyTable: {
/open':{
target:"https://www.sojson.com/", // 目标
changeOrigin: true, //是否跨域
pathRewrite: {
'^/open': '/open'
}
}
}
}
this.$ajax({
method: "post",
url: '/open/api/weather/json.shtml',
params: {
city: '北京'
}
})then(({data}) => {
if (data.message === "success") {
console.log(data.data)
}
});
https://www.jianshu.com/p/495535eb063e vue项目使用webpack-dev-server调用第三方接口跨域配置
接口请求封装:http.js
import axios from 'axios' const TIME_OUT_MS = * // 默认请求超时时间 /*
* @param response 返回数据列表
*/
function handleResults (response) {
let remoteResponse = response.data
var result = {
success: false,
message: '',
status: [],
errorCode: '',
data: {
total: ,
results: []
}
}
if (remoteResponse.success) {
result.data.results = remoteResponse.data
result.data.total = remoteResponse.total
result.success = true
}
if (!remoteResponse.success) {
let code = remoteResponse.errorCode
if (code === ) {
console.log('传参错误')
}
result.errorCode = remoteResponse.errorCode
result.message = remoteResponse.message
}
return result
} function handleUrl (url) {
url = BASE_URL + url
// BASE_URL是接口的ip前缀,比如http:10.100.1.1:8989/
return url
} /*
* @param data 参数列表
* @return
*/
function handleParams (data) {
return data
} export default {
/*
* @param url
* @param data
* @param response 请求成功时的回调函数
* @param exception 异常的回调函数
*/
post (url, data, response, exception) {
axios({
method: 'post',
url: handleUrl(url),
data: handleParams(data),
timeout: TIME_OUT_MS,
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(
(result) => {
response(handleResults(result))
}
).catch(
(error) => {
if (exception) {
exception(error)
} else {
console.log(error)
}
}
)
},
/*
* get 请求
* @param url
* @param response 请求成功时的回调函数
* @param exception 异常的回调函数
*/
get (url, response, exception) {
axios({
method: 'get',
url: handleUrl(url),
timeout: TIME_OUT_MS,
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(
(result) => {
response(handleResults(result))
}
).catch(
(error) => {
if (exception) {
exception(error)
} else {
console.log(error)
}
}
)
},
/*
* 导入文件
* @param url
* @param data
* @param response 请求成功时的回调函数
* @param exception 异常的回调函数
*/
uploadFile (url, data, response, exception) {
axios({
method: 'post',
url: handleUrl(url),
data: handleParams(data),
dataType: 'json',
processData: false,
contentType: false
}).then(
(result) => {
response(handleResults(result, data))
}
).catch(
(error) => {
if (exception) {
exception(error)
} else {
console.log(error)
}
}
)
},
/*
* 下载文件用,导出 Excel 表格可以用这个方法
* @param url
* @param param
* @param fileName 如果是导出 Excel 表格文件名后缀最好用.xls 而不是.xlsx,否则文件可能会因为格式错误导致无法打开
* @param exception 异常的回调函数
*/
downloadFile (url, data, fileName, exception) {
axios({
method: 'post',
url: handleUrl(url),
data: handleParams(data),
responseType: 'blob'
}).then(
(result) => {
const excelBlob = result.data
if ('msSaveOrOpenBlob' in navigator) {
// Microsoft Edge and Microsoft Internet Explorer 10-11
window.navigator.msSaveOrOpenBlob(excelBlob, fileName)
} else {
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
const blob = new Blob([excelBlob])
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
document.body.removeChild(elink)
}
}
).catch(
(error) => {
if (exception) {
exception(error)
} else {
console.log(error)
}
}
)
},
uploadFileFormData (url, data, response, exception) {
axios({
method: 'post',
url: handleUrl(url),
data: data,
timeout: TIME_OUT_MS,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(
(result) => {
response(handleResults(result))
}
).catch(
(error) => {
if (exception) {
exception(error)
} else {
console.log(error)
}
}
)
}
}
接口api统一封装: ports.js
export default {
manage: {
register: '/manage/company/register', // 注册接口
login: '/manage/company/login', // 登录
logout: '/manage/company/loginOut' // // 退出
},
pwd: {
sendEmail: '/manage/user/sendEmail',
resetPwd: '/manage/user/passwordReset'
}
}
引入和定义方式:main.js中
import http from 'http.js'
import ports from 'ports'
Vue.prototype.http = http
Vue.prototype.ports = ports
使用 方式:组件内
this.http.post(this.ports.manage.login, {
userAccount: 'test',
userPassword: '',
cert: ''
}, res => {
if (res.success) {
// 返回正确的处理
} else {
// 返回错误的处理
}
})
https://www.jianshu.com/p/72d911b6d61d vue-cli项目中axios接口封装以及api的统一管理
Vue项目中的http请求统一管理的更多相关文章
- 分享我在 vue 项目中关于 api 请求的一些实现及项目框架
本文主要简单分享以下四点 如何使用 axios 如何隔离配置 如何模拟数据 分享自己的项目框架 本文主要目的为以下三点 希望能够帮到一些人 希望能够得到一些建议 奉上一个使用Vue的模板框架 我只是把 ...
- 介绍vue项目中的axios请求(get和post)
一.先安装axios依赖,还有qs依赖 npm install axios --save npm install qs --save qs依赖包用post请求需要用到的 插入一个知识点: npm in ...
- Vue + webpack 项目配置化、接口请求统一管理
准备工作 需求由来: 当项目越来越大的时候提高项目运行编译速度.压缩代码体积.项目维护.bug修复......等等成为不得不考虑而且不得不做的问题. 又或者后面其他同事接手你的模块,或者改你的bug ...
- vue项目中Webpack-dev-server的proxy用法
问题:在VUE项目中,需要请求后台接口获取数据,这时往往会出现跨域问题 解决方法:在vue.config.js中devServer配置proxy 常用的场景 1. 请求/api/XXX现在都会代理到请 ...
- <转载> VUE项目中CSS管理
vue的scoped 在vue项目中,当 .vue文件中 <style> 标签有 *scoped 属性时,它的 CSS 只作用于当前组件中的元素,很好的实现了样式私有化的目的. 使用sco ...
- Vue项目中使用Vuex + axios发送请求
本文是受多篇类似博文的影响写成的,内容也大致相同.无意抄袭,只是为了总结出一份自己的经验. 一直以来,在使用Vue进行开发时,每当涉及到前后端交互都是在每个函数中单独的写代码,这样一来加大了工作量,二 ...
- 在webpack搭建的vue项目中如何管理好后台接口地址
在最近做的vue项目中,使用了webpack打包工具,以前在做项目中测试环境和生产环境的接口地址都是一样的,由于现在接口地址不一样,需要在项目打包的时候手动切换不同的地址,有时候忘记切换就要重新打包, ...
- 浅谈 Axios 在 Vue 项目中的使用
介绍 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. 特性 它主要有如下特性: 浏览器端发起XMLHttpRequests请求 Node端发起http ...
- 在vue项目中, mock数据
1. 在根目录下创建 test 目录, 用来存放模拟的 json 数据, 在 test 目录下创建模拟的数据 data.json 文件 2.在build目录下的 dev-server.js的文件作如下 ...
随机推荐
- djangoform表单使用验证码
8.1.安装captcha 直接安装:pip install django-simple-captcha Django自动帮我们安装了相关的依赖库six.olefile和Pillow,其中的Pillo ...
- 剑指Offer(二十九):最小的K个数
剑指Offer(二十九):最小的K个数 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/baid ...
- vuex 随笔
vuex刷新数据消失问题: 在项目的入口页面(App.vue)里添加监听刷新事件: 或者使用插件:npm install vuex-persistedstate --save
- 33、[源码]-AOP原理-获取拦截器链-MethodInterceptor
33.[源码]-AOP原理-获取拦截器链-MethodInterceptor
- post提交主订单数据(gateway)实现httpapi
models.proto syntax = "proto3"; package services; import "google/protobuf/timestamp.p ...
- E:nth-of-type(n)
E:nth-of-type(n) 语法: E:nth-of-type(n) { sRules } 说明: 匹配同类型中的第n个同级兄弟元素E.深圳dd马达 要使该属性生效,E元素必须是某个元素的子元素 ...
- ueditor从word粘贴公式
官网地址http://ueditor.baidu.com Git 地址 https://github.com/fex-team/ueditor 参考博客地址 http://blog.ncmem.com ...
- linux 搭建elk6.8.0集群并破解安装x-pack
一.环境信息以及安装前准备 1.组件介绍 *Filebeat是一个日志文件托运工具,在你的服务器上安装客户端后,filebeat会监控日志目录或者指定的日志文件,追踪读取这些文件(追踪文件的变化,不停 ...
- yii2.0场景的简单使用
一.规则中使用场景规则场景的使用模型层public function rules(){ return [ [['name','product_id'],'required','on'=>'add ...
- jquery validate 表单验证插件 代码
/* 表单验证 */ var signupFormValidator = $("#signupForm").validate({ /* 自定义验证规则 */ rules : { o ...