vue 使用axios 數(shù)據(jù)請(qǐng)求第三方插件的使用教程詳解
axios
基于http客戶端的promise,面向?yàn)g覽器和nodejs
特色
•瀏覽器端發(fā)起XMLHttpRequests請(qǐng)求
•node端發(fā)起http請(qǐng)求
•支持Promise API
•監(jiān)聽(tīng)請(qǐng)求和返回
•轉(zhuǎn)化請(qǐng)求和返回
•取消請(qǐng)求
•自動(dòng)轉(zhuǎn)化json數(shù)據(jù)
•客戶端支持抵御
安裝
使用npm:
$ npm i axiso
為了解決post默認(rèn)使用的是x-www-from-urlencoded 去請(qǐng)求數(shù)據(jù),導(dǎo)致請(qǐng)求參數(shù)無(wú)法傳遞到后臺(tái),所以還需要安裝一個(gè)插件QS
$ npm install qs
一個(gè)命令全部解決
$ npm install --save axios vue-axios qs
兩種方法在vue中使用 axios
方法-:修改原型鏈
首先在 main.js 中引入 axios
import Axiso from 'axiso'
這時(shí)候如果在其它的組件中,是無(wú)法使用 axios 命令的。但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個(gè)問(wèn)題
Vue.prototype.$axios= Axios
配置好了之后就可以全局使用了
示例:在main.js使用
Get請(qǐng)求:
//發(fā)起一個(gè)user請(qǐng)求,參數(shù)為給定的ID
$axios.get('/user?ID=1234')
.then(function(respone){
console.log(response);
})
.catch(function(error){
console.log(error);
});
Post請(qǐng)求
$axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
為了保證請(qǐng)求的數(shù)據(jù)正確,可以在main.js配置如下內(nèi)容:
Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口請(qǐng)求地址 Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情況使用 Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置請(qǐng)求頭信息。
那么最基本的配置已經(jīng)完成了,但是還有一個(gè)問(wèn)題,既然是前后端分離,那么肯定避免不了跨域請(qǐng)求數(shù)據(jù)的問(wèn)題,接下來(lái)就是配置跨域了。
在config/index.js里面的dev里面配置如下代碼:
proxyTable: {
'/api': {
target: 'http://xxx.xxx.xxx.xxx:8081/',//設(shè)置你調(diào)用的接口域名和端口號(hào) 別忘了加http
changeOrigin: true,
pathRewrite: {
'^/api': '/'//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時(shí)直接用api代替 比如我要調(diào)用'http://xxx.xxx.xxx.xx:8081/user/add',直接寫‘/api/user/add'即可
}
}
完整代碼:
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://xxx.xxx.xxx.xxx:8081/',//設(shè)置你調(diào)用的接口域名和端口號(hào) 別忘了加http
changeOrigin: true,
pathRewrite: {
'^/api': '/'//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時(shí)直接用api代替 比如我 要調(diào)用'http://xxx.xxx.xxx.xxx:8081/user/add',直接寫‘/api/user/add'即可
}
}
},
但是注意了,這只是開(kāi)發(fā)環(huán)境(dev)中解決了跨域問(wèn)題,生產(chǎn)環(huán)境中真正部署到服務(wù)器上如果是非同源還是存在跨域問(wèn)題.
axios攔截器的使用
當(dāng)我們?cè)L問(wèn)某個(gè)地址頁(yè)面時(shí),有時(shí)會(huì)要求我們重新登錄后再訪問(wèn)該頁(yè)面,也就是身份認(rèn)證失效了,如token丟失了,或者是token依然存在本地,但是卻失效了,所以單單判斷本地有沒(méi)有token值不能解決問(wèn)題。此時(shí)請(qǐng)求時(shí)服務(wù)器返回的是401錯(cuò)誤,授權(quán)出錯(cuò),也就是沒(méi)有權(quán)利訪問(wèn)該頁(yè)面。
我們可以在發(fā)送所有請(qǐng)求之前和操作服務(wù)器響應(yīng)數(shù)據(jù)之前對(duì)這種情況過(guò)濾。
// http request 請(qǐng)求攔截器,有token值則配置上token值
axios.interceptors.request.use(
config => {
if (token) { // 每次發(fā)送請(qǐng)求之前判斷是否存在token,如果存在,則統(tǒng)一在http請(qǐng)求的header都加上token,不用每次請(qǐng)求都手動(dòng)添加了
config.headers.Authorization = token;
}
return config;
},
err => {
return Promise.reject(err);
});
// http response 服務(wù)器響應(yīng)攔截器,這里攔截401錯(cuò)誤,并重新跳入登頁(yè)重新獲取token
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
// 這里寫清除token的代碼
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath}//登錄成功后跳入瀏覽的當(dāng)前頁(yè)面
})
}
}
return Promise.reject(error.response.data)
});
安裝qs插件后的簡(jiǎn)化操作
$ npm install qs import QS from 'qs'
//axios攔截器
// 超時(shí)時(shí)間
Axios.defaults.timeout = 5000;
// http請(qǐng)求攔截器 請(qǐng)求之前的一些操作
Axios.interceptors.request.use(config => {
if(config.method=='post'){
config.data=QS.stringify(config.data);//防止post請(qǐng)求參數(shù)無(wú)法傳到后臺(tái)
}
return config
}, error => {
Message.error({
message: '加載超時(shí)'
});
return Promise.reject(error)
});
// http響應(yīng)攔截器 請(qǐng)求之后的操作
Axios.interceptors.response.use(data => {
return data
}, error => {
Message.error({
message: '加載失敗'
});
return Promise.reject(error)
});
<span style="color: rgb(255, 0, 0);"> if(config.method=='post'){
config.data=QS.stringify(config.data);//防止post請(qǐng)求參數(shù)無(wú)法傳到后臺(tái)
}</span><br>這句可以直接代替
<span style="color: rgb(255, 0, 0);">Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口請(qǐng)求地址 Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情況使用 Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置請(qǐng)求頭信息。</span>
<br><span style="font-size: 14pt;">vue 訪問(wèn)本地json文件的數(shù)據(jù)測(cè)試配置方法<br>第一步,準(zhǔn)備json數(shù)據(jù)<br>json文件位置:src/data/data.json<br>第二步,配置webpack.dev.conf.js 文件<br>在webpack.dev.config.js 里面添加如下代碼:<br></span>
// webpack.dev.conf.js
// 通過(guò)express導(dǎo)入路由
const express = require('express')
const app = express()
var appData = require('../src/data/data.json')
// json賣家數(shù)據(jù)
var seller = appData.seller
// json商品數(shù)據(jù)
var goods = appData.goods
// json評(píng)論數(shù)據(jù)
var ratings = appData.ratings
// 編寫路由
var apiRoutes = express.Router()
// 所有通過(guò)接口相關(guān)的api都會(huì)通過(guò)api這個(gè)路由導(dǎo)向到具體的路由
app.use('/api', apiRoutes)
//devServer下寫入如下代碼:
before(app) {
app.get('/api/seller', (req, res) => {
res.json({
errno: 0,
data: seller
})//接口返回json數(shù)據(jù),上面配置的數(shù)據(jù)seller就賦值給data請(qǐng)求后調(diào)用
}),
app.get('/api/goods', (req, res) => {
res.json({
errno: 0,
data: goods
})
}),
app.get('/api/ratings', (req, res) => {
res.json({
errno: 0,
data: ratings
})
})
}
按照如上配置就大功告成了,webpack.dev.config.js 完整代碼如下:
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
// webpack.dev.conf.js
// 通過(guò)express導(dǎo)入路由
const express = require('express')
const app = express()
var appData = require('../src/data/data.json')
// json賣家數(shù)據(jù)
var seller = appData.seller
// json商品數(shù)據(jù)
var goods = appData.goods
// json評(píng)論數(shù)據(jù)
var ratings = appData.ratings
// 編寫路由
var apiRoutes = express.Router()
// 所有通過(guò)接口相關(guān)的api都會(huì)通過(guò)api這個(gè)路由導(dǎo)向到具體的路由
app.use('/api', apiRoutes)
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
},
before(app) {
app.get('/api/seller', (req, res) => {
res.json({
errno: 0,
data: seller
})//接口返回json數(shù)據(jù),上面配置的數(shù)據(jù)seller就賦值給data請(qǐng)求后調(diào)用
}),
app.get('/api/goods', (req, res) => {
res.json({
errno: 0,
data: goods
})
}),
app.get('/api/ratings', (req, res) => {
res.json({
errno: 0,
data: ratings
})
})
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
main.js完整代碼如下:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
import QS from 'qs'
Vue.prototype.$axios=Axios //原型鏈配置
Vue.config.productionTip = false
//axios攔截器
// 超時(shí)時(shí)間
Axios.defaults.timeout = 5000;
// http請(qǐng)求攔截器
Axios.interceptors.request.use(config => {
if(config.method=='post'){
config.data=QS.stringify(config.data);//防止post請(qǐng)求參數(shù)無(wú)法傳到后臺(tái)
}
return config
}, error => {
Message.error({
message: '加載超時(shí)'
});
return Promise.reject(error)
});
// http響應(yīng)攔截器
Axios.interceptors.response.use(data => {
return data
}, error => {
Message.error({
message: '加載失敗'
});
return Promise.reject(error)
});
// 注冊(cè)一個(gè)全局自定義指令 `v-focus`
Vue.directive('focus', {
// 當(dāng)被綁定的元素插入到 DOM 中時(shí)……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
本地成功請(qǐng)求數(shù)據(jù)效果:

<span style="font-size: 14pt;"> </span>
總結(jié)
以上所述是小編給大家介紹的vue 使用axios 數(shù)據(jù)請(qǐng)求第三方插件的使用教程詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- Vue二次封裝axios為插件使用詳解
- vue下axios攔截器token刷新機(jī)制的實(shí)例代碼
- Vue學(xué)習(xí)之a(chǎn)xios的使用方法實(shí)例分析
- vue 對(duì)axios get pust put delete封裝的實(shí)例代碼
- Vue axios 將傳遞的json數(shù)據(jù)轉(zhuǎn)為form data的例子
- Vue 設(shè)置axios請(qǐng)求格式為form-data的操作步驟
- 關(guān)于Vue中axios的封裝實(shí)例詳解
- vue中axios的二次封裝實(shí)例講解
- vue+axios實(shí)現(xiàn)post文件下載
- vue + axios get下載文件功能
- Vue CLI項(xiàng)目 axios模塊前后端交互的使用(類似ajax提交)
- vue簡(jiǎn)單封裝axios插件和接口的統(tǒng)一管理操作示例
相關(guān)文章
Vue組合式API如何正確解構(gòu)props不會(huì)丟失響應(yīng)性
響應(yīng)式?API?賦予了組合式?API?一大坨可能性的同時(shí),代碼精簡(jiǎn),雖然但是,我們應(yīng)該意識(shí)到響應(yīng)性的某些陷阱,比如丟失響應(yīng)性,在本文中,我們將學(xué)習(xí)如何正確解構(gòu)?Vue?組件的?props,使得?props?不會(huì)丟失響應(yīng)性2024-01-01
vue使用Office?Web實(shí)現(xiàn)線上文件預(yù)覽
這篇文章主要為大家介紹了vue使用微軟的開(kāi)發(fā)接口Office?Web,實(shí)現(xiàn)線上文件預(yù)覽,預(yù)覽word,excel,pptx,pdf文件,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Vue單頁(yè)面應(yīng)用做預(yù)渲染的方法實(shí)例
vue是一個(gè)單頁(yè)面的應(yīng)用,這導(dǎo)致一些爬蟲和百度無(wú)法搜索到,如果你想針對(duì)你應(yīng)用的其中某些頁(yè)面進(jìn)行SEO優(yōu)化,讓他們可以被爬蟲和百度搜索到,你可以進(jìn)行預(yù)渲染操作,下面這篇文章主要給大家介紹了關(guān)于Vue單頁(yè)面應(yīng)用做預(yù)渲染的相關(guān)資料,需要的朋友可以參考下2021-10-10
element-ui中導(dǎo)航組件menu的一個(gè)屬性:default-active說(shuō)明
這篇文章主要介紹了element-ui中導(dǎo)航組件menu的一個(gè)屬性:default-active說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
詳解Vue3?SFC?和?TSX?方式調(diào)用子組件中的函數(shù)
在使用?.vue?定義的組件中,setup?中提供了?defineExpose()?方法,該方法可以將組件內(nèi)部的方法暴露給父組件,這篇文章主要介紹了Vue3?SFC?和?TSX?方式調(diào)用子組件中的函數(shù),需要的朋友可以參考下2022-10-10

