1、跨域配置:在config中的index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: "http://192.168.3.898:8080", // 目标地址
changeOrigin: true, // 是否跨域
pathRewrite: { // 重定向地址
// '^/apis': '' // 后台地址上有api,不用重定向
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8081, // 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, // https://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
*/
// https://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
// https://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,
// https://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
},
css: {
loaderOptions: {
less: {
lessOptions: {
modifyVars: {
'primary-color': '#1DA57A',
'link-color': '#1DA57A',
'border-radius-base': '2px',
},
javascriptEnabled: true,
},
},
},
},
}
2、在src中新建一个api文件夹。里面新建一个文件http.js(axios配置以及请求拦截响应拦截)
import axios from 'axios' // 引用axios
// axios 配置
const Axios = axios.create({
// baseURL: '/api/',// 是用于请求的服务器 URL 这是调用数据接口,公共接口url+调用接口名
timeout: 5000, // 请求超时时间 如果请求花费了超过 `timeout` 的时间,请求将被中断
headers: { // 自定义请求头
// 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
'Content-type': 'application/json; charset=UTF-8'
}
})
// 请求拦截可以携带token等一些信息发送给后台,可以在响应拦截里面监听后台返回的状态码,进行数据处理和特定的路由跳转
// 添加请求拦截器
Axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么?手动传递token
// 1.获取token
var token = sessionStorage.getItem('token')
if (token) {
// token拼接Bearer空格请求接口权限
let newToken = token
// 2.必须在请求头中使用 Authorization 字段提供 token 令牌,请求时头部带上token
config.headers.Authorization = newToken
}
return config
}, function (error) {
// 对请求错误做些什么
this.$message.error('请求超时')
return Promise.reject(error)
})
// http response 返回拦截器
Axios.interceptors.response.use(
response => {
// 跟后台定义好返回的成功失败判断
if (response) {
// 成功返回数据
} else {
// 请求失败提示返回错误提示
// console.log(response.data.msg)
}
// 返回数据格式定好,前端可自定义直接返回第几层data
return response
},
error => {
return Promise.reject(error.response)
}
)
export default Axios
/**
* get 请求方法
* @param url
* @param params
* @returns {Promise}
*/
// export function get (url, params = {}) {
// return new Promise((resolve, reject) => {
// Axios
// .get(url, {
// params: params
// })
// .then(response => {
// resolve(response)
// })
// .catch(err => {
// reject(err)
// })
// })
// }
/**
* post 请求方法
* @param url
* @param data
* @returns {Promise}
*/
// export function post (url, data = {}) {
// return new Promise((resolve, reject) => {
// Axios.post(url, data).then(
// response => {
// // console.log(response.data.code)
// resolve(response.data)
// },
// err => {
// reject(err)
// }
// )
// })
// }
3、在api文件夹中再新建一个文件index.js(后台请求接口封装)
/**
* api接口统一管理
*/
import Axios from '@/api/http'
// 获取验证码
export const getCode = () => {
return Axios({
method: 'get',
url: '/api/captchaImage',
})
}
// 登录
export const login = (data) => {
return Axios({
method: 'post',
url: '/api/login',
data,
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
// 获取测站类型下拉数据
export const getType = () => {
return Axios({
method: 'get',
url: '/api/app/swStation/type/list'
})
}
// 获取测站管理表格数据
export const getData = (num, size) => {
return Axios({
method: 'get',
url: '/api/app/swStation/list', params: {
pageNum: num,
pageSize: size
}, // 字符串拼接
headers: {
'Content-Type': 'application/json'
} // 设置请求头
})
}
(注意get请求参数url的拼接以及自定义请求头)
4、在组件中使用接口
get请求(无参数)
getCode() {
getCode()
.then(res => {
if(res.data.code == 0) {
this.code = res.data.data.verifyCode
this.uuid = res.data.data.uuid
// 调用登录接口
this.getToken()
}
})
},
get请求(有参数)
getData() {
getData(1, 10)
.then(res => {
console.log(res)
this.data = res.data.data
})
.catch(err => {
console.log(err)
})
},
post请求
getToken() {
// formData格式
let params = new FormData()
params.append('captcha', this.code)
params.append('password', '654321')
params.append('username', 'wss')
params.append('uuid', this.uuid)
login(params)
.then(res => {
// 存储token
sessionStorage.setItem('token', res.data.data.token)
})
},
(数据格式和请求头是后台定义的,所以就跟着来了。)
时光永远继续,日子永远向前。