vue接口封装:
第一步:解决跨域
接口请求,一般都会碰到跨域问题,在vue项目中,我们采用页面代理的方法解决跨域问题:
文件config——index.js文件
index.js
\
use strict'
// Template version: 1.2.7
// see vuejs-templates.github.io/webpack for documentation.
const path = require('path');
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target:'www.XXX.com/jcrh', // 请求的第三方接口 或 后端,线上接口
// target:'http://localhost:8081/api', // 本地
changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
secure: true, //true是https false是http
pathRewrite:{ // 路径重写,
'^/api': '' // 替换target中的请求地址,也就是说以后你在请求api.douban.com/v2/XXXXX这个地…
}
},
//物联网气泡接口代理
'/web': {
target: 'api.XXX.com/rest',//微后端…
changeOrigin: true,
pathRewrite: {
'^/web': ''
}
}
},
// Various Dev Server settings
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false, //是否默认,启动项目自动打开页面 true自动打开 false手动
errorOverlay: true,
notifyOnErrors: true,
poll: false, // webpack.js.org/configurati…
/**
* Source Maps
*/
// webpack.js.org/configurati…
devtool: 'eval-source-map',
cacheBusting: true,
cssSourceMap: false,
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
/**
* Source Maps
*/
productionSourceMap: false,
devtool: '#source-map',
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
}
}
第二部:接口封装
我们约定俗成一般会在src文件下建立一个api文件
这个api文件,就相当于一个管理接口的仓库
api——index.js
第三部:接口运用
index.vue