安裝axios
npm install axios --save
新建一個(gè)js文件,http.js,在這里我給headers自定了token,所以我們發(fā)送的請(qǐng)求都是非簡(jiǎn)單請(qǐng)求,而發(fā)送了非簡(jiǎn)單請(qǐng)求,就會(huì)每次發(fā)送請(qǐng)求的時(shí)候觸發(fā)一個(gè)預(yù)檢測(cè)請(qǐng)求,也就是options請(qǐng)求,所以就要實(shí)現(xiàn)跨域。
import axios from 'axios'
import { Message } from 'element-ui'; //element庫的消息提示,可以不用
import router from "../router";
import store from '../store'
//創(chuàng)建axios實(shí)例
var service = axios.create({
baseURL: '/api',
timeout: 5000,
headers: {
'Content-type': 'application/json',
'contentType': 'application/x-www-form-urlencoded',
'token' : localStorage.getItem('userToken')
}
})
export default {
params(url,param,cback,reject,method){
service({
method: method,
url,
[method === 'get' || method === 'delete' ? 'params' : 'data'] : param,
}).then(res => {
//axios返回的是一個(gè)promise對(duì)象
var res_code = res.status.toString();
if (res_code.charAt(0) == 2) {
cback(res); //cback在promise執(zhí)行器內(nèi)部
} else {
console.log(res, '異常1')
}
}).catch(err => {
if(err.response.data.msg === '請(qǐng)登錄'){
Message({
showClose: true,
message: '您的身份已過期,請(qǐng)重新登錄',
type: 'error'
});
store.dispatch('Login', null);
router.push("/login");
}else if(err.response.data.msg === '授權(quán)不足'){
Message({
showClose: true,
message: '您的權(quán)限不足,如有需要,請(qǐng)聯(lián)系開發(fā)人員',
type: 'error'
});
}
})
},
//get請(qǐng)求,其他類型請(qǐng)求復(fù)制粘貼,修改method
get(url, param,method) {
return new Promise((cback, reject) => {
this.params(url,param,cback,reject,method)
})
},
post(url, param,method) {
return new Promise((cback, reject) => {
this.params(url,param,cback,reject,method)
})
},
put(url, param,method) {
return new Promise((cback, reject) => {
this.params(url,param,cback,reject,method)
})
},
delete(url, param,method) {
return new Promise((cback, reject) => {
this.params(url,param,cback,reject,method)
})
},
}
main.js中引入這個(gè)文件,做全局使用
prototype屬性是JS用法,每一個(gè)構(gòu)造函數(shù)都有一個(gè)屬性叫做原型(prototype),默認(rèn)情況下prototype屬性會(huì)默認(rèn)獲得一個(gè)constructor(構(gòu)造函數(shù))屬性
//這里是vue的主js入口文件
import Vue from 'vue'
import App from './App.vue'
import http from './http.js' //axios實(shí)例化后引入取名http
Vue.prototype.http = http //放入全局
new Vue({
render: h => h(App)
}).$mount('#app')
組件中調(diào)用封裝的axios方式,大家記得傳參數(shù),依次是地址,參數(shù),請(qǐng)求方式:
<script>
//生命周期函數(shù)
mounted (){
this.http.get('banner/1').then(res=>{
console.log(res.data)
})
}
</script>
因?yàn)槭欠呛?jiǎn)單請(qǐng)求,肯定存在跨域問題,我當(dāng)時(shí)由于沒徹底解決跨域問題,導(dǎo)致options請(qǐng)求重定向我這邊就報(bào)302錯(cuò)誤。導(dǎo)致爬了很久坑。
- 在config文件中的index.js里面進(jìn)行配置代理,我們知道同源策略只是在瀏覽器中存在,不存在于服務(wù)器中。因此我們可以將需要跨域請(qǐng)求的地址轉(zhuǎn)發(fā)給我們自己的服務(wù)器然后委托服務(wù)器去請(qǐng)求信息。
- 在dev里面進(jìn)行配置proxyTable用作代理
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: "http://47.93.240.205:8800", //服務(wù)器域名
changeOrigin: true,
pathRewrite: {
'^/api': '/api' // 這種接口配置出來 http://XX.XX.XX.XX:8083/api/login
}
}
},