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的文件作如下 ...
随机推荐
- Android笔记(二十二) Android中的GridView
GridView和ListView一样,是Android中比较常见的布局控件,譬如我们的手机桌面其实就是一个GridView. 效果: 实现过程和ListView类似,也是通过Adapter将数据源展 ...
- Android笔记(十四) Android中的基本组件——按钮
Android中的按钮主要包括Button和ImageButton两种,Button继承自TextView,而ImageButton继承自ImageView.Button生成的按钮上显示文字,而Ima ...
- linux-centos7.6设置固定IP网络方法
两种方法设置固定IP 本文分别用了虚拟机网络模式桥接模式和Net模式,至于两者直接的区别可查看其他文档. 一.安装时设置固定IP地址 1.在系统设置界面,点击“网络和主机名”选项,可以看到默认是未连接 ...
- wxpython中设置radiobox相关使用
#coding=utf-8 import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,-1, ...
- Yum三方仓库——EPEL
参考:什么是EPEL 及 Centos上安装EPEL 参考:How to Enable EPEL Repository for RHEL/CentOS 7.x/6.x/5.x 前言 RHEL以及他的衍 ...
- Tkinter关于新建窗口内Entry无法获取值(值全为空)的解决办法
最近在做Python的课程作业,遇到一个问题,描述如下: 使用Python内置的Tkinter模块进行GUI编程 给一个按钮(或菜单)绑定事件,打开一个新窗口,新窗口内有Entry若干,通过textv ...
- Luogu P1276 校门外的树(增强版)
Luogu P1276 校门外的树(增强版) 本来看着是道普及-,就不打算写博客了,结果因为出了3次错,调试了15min就还是决定写一下-- 本题坑点: 1.每个位置有三种情况:空穴,树苗,树(而不只 ...
- P1880 [NOI1995]石子合并[环形DP]
题目来源:洛谷 题目描述 在一个圆形操场的四周摆放N堆石子,现要将石子有次序地合并成一堆.规定每次只能选相邻的2堆合并成新的一堆,并将新的一堆的石子数,记为该次合并的得分. 试设计出1个算法,计算出将 ...
- python_反射:应用
class User(object): def denglu(self): print('欢迎来到登录页面!') def zhuce(self): print('欢迎来到注册页面!') def you ...
- 神经网络(1)--Non-linear hypotheses,为什么我们要学习神经网络这种算法来处理non-linear hypotheses
神经网络(1)--No-linear hypotheses 为什么我们已经有了linear regression与logistic regression算法还要来学习神经网络这个另外的算法呢,让我们来 ...