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请求统一管理的更多相关文章

  1. 分享我在 vue 项目中关于 api 请求的一些实现及项目框架

    本文主要简单分享以下四点 如何使用 axios 如何隔离配置 如何模拟数据 分享自己的项目框架 本文主要目的为以下三点 希望能够帮到一些人 希望能够得到一些建议 奉上一个使用Vue的模板框架 我只是把 ...

  2. 介绍vue项目中的axios请求(get和post)

    一.先安装axios依赖,还有qs依赖 npm install axios --save npm install qs --save qs依赖包用post请求需要用到的 插入一个知识点: npm in ...

  3. Vue + webpack 项目配置化、接口请求统一管理

    准备工作 需求由来: 当项目越来越大的时候提高项目运行编译速度.压缩代码体积.项目维护.bug修复......等等成为不得不考虑而且不得不做的问题.  又或者后面其他同事接手你的模块,或者改你的bug ...

  4. vue项目中Webpack-dev-server的proxy用法

    问题:在VUE项目中,需要请求后台接口获取数据,这时往往会出现跨域问题 解决方法:在vue.config.js中devServer配置proxy 常用的场景 1. 请求/api/XXX现在都会代理到请 ...

  5. <转载> VUE项目中CSS管理

    vue的scoped 在vue项目中,当 .vue文件中 <style> 标签有 *scoped 属性时,它的 CSS 只作用于当前组件中的元素,很好的实现了样式私有化的目的. 使用sco ...

  6. Vue项目中使用Vuex + axios发送请求

    本文是受多篇类似博文的影响写成的,内容也大致相同.无意抄袭,只是为了总结出一份自己的经验. 一直以来,在使用Vue进行开发时,每当涉及到前后端交互都是在每个函数中单独的写代码,这样一来加大了工作量,二 ...

  7. 在webpack搭建的vue项目中如何管理好后台接口地址

    在最近做的vue项目中,使用了webpack打包工具,以前在做项目中测试环境和生产环境的接口地址都是一样的,由于现在接口地址不一样,需要在项目打包的时候手动切换不同的地址,有时候忘记切换就要重新打包, ...

  8. 浅谈 Axios 在 Vue 项目中的使用

    介绍 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. 特性 它主要有如下特性: 浏览器端发起XMLHttpRequests请求 Node端发起http ...

  9. 在vue项目中, mock数据

    1. 在根目录下创建 test 目录, 用来存放模拟的 json 数据, 在 test 目录下创建模拟的数据 data.json 文件 2.在build目录下的 dev-server.js的文件作如下 ...

随机推荐

  1. SQL SERVER-LinkServer搬迁

    选中linkserver,按F7打开对象游览器, 选中linkserver,生成脚本. 把密码填入脚本运行即可 USE [master] GO /****** Object: LinkedServer ...

  2. 解决npm安装时出现run `npm audit fix` to fix them, or `npm audit` for details 的问题

    npm audit fix npm audit fix --force npm audit 按照顺序一一运行亲测完全可用如果还是不行的话,可以把node_modules和package-lock.js ...

  3. 【异常】jps6432 -- process information unavailable

    1 现象

  4. python 获取本机的 IP 地址,windows,linux均可

    #encoding=utf-8 #参考csdn某篇文章 import socket def get_host_ip(): """ 查询本机ip地址 :return: ip ...

  5. 判断字符串是否是IP地址

    #include <stdio.h>#include <string.h> bool isIP(const char* str); int main(){ char str[] ...

  6. 01_第一次如何上传GitHub(转)Updates were rejected because the tip of your current branch is behind

    https://www.cnblogs.com/code-changeworld/p/4779145.html 刚创建的github版本库,在push代码时出错: $ git push -u orig ...

  7. 02_Tutorial 2: Requests and Responses 请求和响应

    1.请求和响应 1.文档 https://www.django-rest-framework.org/tutorial/2-requests-and-responses/ https://q1mi.g ...

  8. Kylin介绍 (很有用)

    转:http://blog.csdn.net/yu616568/article/details/48103415 Kylin是ebay开发的一套OLAP系统,与Mondrian不同的是,它是一个MOL ...

  9. MongoDB空间分配

    Mongodb占据的磁盘空间比MySQL大得多,可以理解文档数据如Json这种格式,存在许多冗余数据,但空间占用大得不正常,甚至是传统数据库的三四倍,不太契合工程实践,应该有改善的余地. 查阅了一些资 ...

  10. xlrd/xlwt

    操作 xls格式的excel文件 读模块 xlrd import xlrd 打开文件 wb= xlrd.open_workbook('xxxx.xls') 获取excel中的表 ws= wb.shee ...