VUE腳手架axios中 跨域 實例 并發(fā) 全局 攔截

VUE腳手架axios官方網(wǎng)址:

https://www.kancloud.cn/yunye/axios/234845

需要在文檔安裝?npm install axios 才能使用 axios

1.并發(fā)請求:

<template>

? <div id="app">


? </div>

</template>

<script>

import axios from 'axios'

export default {

? name: 'App',

? data(){

? return{

? ? url1:'https://cno..................',

? ? url2:'https://cno.........................'

? }

? },

? /* 執(zhí)行多個并發(fā)請求 */

? created(){

? ? Promise.all([axios.get(this.url1), ?axios.get(this.url2)])

? ? .then(res=>{

? ? ? ? ?console.log(res);

? ? })

? ? /* 和上面Promise 方法類似 但是Promise只返回一個數(shù)組 */

? ?axios.all( ?[axios.get(this.url1), ?axios.get(this.url2)] )

? ?.then( axios.spread( (res1,res2)=>{

? ? ?/* 兩個請求都請求完畢了,再返回結果 */

? ? ? ?console.log(res1);

? ? ? ?console.log(res2);

? ?}))

? }

}

</script>

<style>

#app {

? font-family: Avenir, Helvetica, Arial, sans-serif;

? -webkit-font-smoothing: antialiased;

? -moz-osx-font-smoothing: grayscale;

? text-align: center;

? color: #2c3e50;

? margin-top: 60px;

}

</style>

2.跨域 實例 全局 攔截:

跨域:建立一個簡單的js文檔:

let http = require('http')

http.createServer((req,res)=>{

? ? /* 這句話是允許跨域用的 */

? ? // res.setHeader('Access-Control-Allow-Origin','*')

? ? /* 下面是后端返回的結果 */

? ? res.end('yousuccess')

? ? /* 3000是端口 */

}).listen(3000,function(){

? ? console.log('server start...')

})

在vue.config.js文件中配置一下:

const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({

? transpileDependencies: true,

? devServer: {

? ? proxy: {

? ? ? '/api': {

? ? ? ? target: 'http://localhost:3000/'

? ? ? }

? ? }

? }

})

主文件App.vue:

<template>

? <div id="app">

? ?<button @click="login">登 錄</button>

? ?<button @click="getUser">獲取用戶</button>

? ?<button @click="getList">所有權限列表</button>

? ?<child-a></child-a>

? </div>

</template>

<script>

import axios from 'axios'

import ChildA from '@/components/ChildA.vue'

export default {

? name: 'App',

? components:{

? ?ChildA

? },

? data(){

? return{

? ? instance:null

? }

? },

? created(){

? ? /* axios.get('/api')

? ? .then(res=>{

? ? ?console.log(res);

? ? }) */


? ? //* 自定義配置新建一個 axios 實例 */

? ? //* 設置了baseURL 使用了這個instance實例都不用把url寫全,直接寫路徑(例如:login)即可 */

? ? /* this.instance = axios.create({

? ? ? baseURL:'http://time.......................',

? ? ? //如果請求花費了超過'timeout'時間,請求將被中斷

? ? ? timeout:3000,

? ? ? //給使用instance這個實例的都配置上Headers

? ? ? headers:{

? ? ? ? ? ?'Authorization':localStorage.token

? ? ? ? ?}

? ? }) */

? ? /* axios 全局配置基本路徑和請求頭 */

? ? axios.defaults.baseURL = 'http://tim................................',

? ? axios.defaults.headers.common['Authorization'] = localStorage.token,

? ? axios.defaults.timeout=3000;


? ? //如果想局部配置 請創(chuàng)建一個實例instance通過實例調接口

? ? //全局配置 添加請求攔截器

? ? //每次發(fā)送接口都會進行攔截

? ? axios.interceptors.request.use(function (config) {

? ? ? //console.log('config',config);

? ? ? //在請求攔截時候 添加請求頭也是可以的

? ? ? config.headers.Authorization = localStorage.token

? ? ? //必須把config return ?出去

? ? ? return config

? ? },function(error) {

? ? ? //對請求錯誤做些什么

? ? ? return Promise.reject(error)

? ? });

? ? //添加響應攔截器

? ? //只要請求有相應 都會先走一遍響應攔截器

? ? axios.interceptors.response.use(function (response) {

? ? ? //對響應數(shù)據(jù)做點什么

? ? ? console.log('response',response);

? ? ? //可以同意給返回數(shù)據(jù) 再添加屬性和值

? ? ? response.data.msg = 'VUE好好學'

? ? ? //response 也是必須要return出去的

? ? ? //可以在響應攔截里面直接把數(shù)據(jù)data返回出去

? ? ? return response.data

? ? },function(error) {

? ? ? ? ?//對請求錯誤做些什么

? ? ? return Promise.reject(error)

? ? })

? },

? mounted(){

? ?/* 獲取元素dom使用,mounted里面dom加載完畢 */

? },

? methods:{

? ? login(){

? ? ? /* this.instance */axios.post('login',{

? ? ? ? username:'admin',

? ? ? ? password:'123456'

? ? ? })

? ? ? .then(res=>{

? ? ? ? console.log(res.data);

? ? ? ? localStorage.token = res.data.token

? ? ? })

? ? },

? ? getUser(){

? ? ?axios.get('users',{

? ? ? ? params:{

? ? ? ? ? pagenum:1,

? ? ? ? ? pagesize:5

? ? ? ? },

? ? ? ? /* 在get配置請求中這樣配置 */

? ? ? ? /* ?headers:{

? ? ? ? ? ?'Authorization':localStorage.token

? ? ? ? ?} */

? ? ? })

? ? ? .then(res=>{

? ? ? ?console.log(res);

? ? ? })

? ? },

? ? getList(){

? ? ? axios.get('right/list')

? ? ? .then(res=>{

? ? ? ? console.log(res);

? ? ? })

? ? }

? }


}

</script>

<style>

#app {

? font-family: Avenir, Helvetica, Arial, sans-serif;

? -webkit-font-smoothing: antialiased;

? -moz-osx-font-smoothing: grayscale;

? text-align: center;

? color: #2c3e50;

? margin-top: 60px;

}

</style>

也可以在main.js文件中設置全局axios:

import Vue from 'vue'

import App from './App.vue'

import axios from 'axios'

Vue.config.productionTip = false

/* 在入口main.js文件導入axios

? ?并掛載到Vue構造函數(shù)的原型下 目的在供所有Vue組件使用

? ? 這樣寫就不用每個vue頁面都導入axios */

? ? Vue.prototype.$axios = axios;

new Vue({

? render: h => h(App),

}).$mount('#app')



?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子贯要,更是在濱河造成了極大的恐慌汉匙,老刑警劉巖十兢,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俊啼,死亡現(xiàn)場離奇詭異,居然都是意外死亡趋观,警方通過查閱死者的電腦和手機稻艰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門懂牧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人尊勿,你說我怎么就攤上這事僧凤。” “怎么了元扔?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵躯保,是天一觀的道長。 經(jīng)常有香客問我澎语,道長途事,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任擅羞,我火速辦了婚禮尸变,結果婚禮上,老公的妹妹穿的比我還像新娘减俏。我一直安慰自己振惰,他們只是感情好,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布垄懂。 她就那樣靜靜地躺著,像睡著了一般痛垛。 火紅的嫁衣襯著肌膚如雪草慧。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天匙头,我揣著相機與錄音漫谷,去河邊找鬼。 笑死蹂析,一個胖子當著我的面吹牛舔示,可吹牛的內容都是我干的碟婆。 我是一名探鬼主播,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼惕稻,長吁一口氣:“原來是場噩夢啊……” “哼竖共!你這毒婦竟也來了?” 一聲冷哼從身側響起俺祠,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤公给,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蜘渣,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體淌铐,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年蔫缸,在試婚紗的時候發(fā)現(xiàn)自己被綠了腿准。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡拾碌,死狀恐怖吐葱,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情倦沧,我是刑警寧澤唇撬,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站展融,受9級特大地震影響窖认,放射性物質發(fā)生泄漏。R本人自食惡果不足惜告希,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一扑浸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧燕偶,春花似錦喝噪、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至伯诬,卻和暖如春晚唇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背盗似。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工哩陕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓悍及,卻偏偏與公主長得像闽瓢,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子心赶,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內容