国产99久久精品_欧美日本韩国一区二区_激情小说综合网_欧美一级二级视频_午夜av电影_日本久久精品视频

最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
當前位置: 首頁 - 科技 - 知識百科 - 正文

vue 使用axios 數據請求第三方插件的使用教程詳解

來源:懂視網 責編:小采 時間:2020-11-27 21:54:03
文檔

vue 使用axios 數據請求第三方插件的使用教程詳解

vue 使用axios 數據請求第三方插件的使用教程詳解:axios 基于http客戶端的promise,面向瀏覽器和nodejs 特色 •瀏覽器端發起XMLHttpRequests請求 •node端發起http請求 •支持Promise API •監聽請求和返回 •轉化請求和返回 •取消請求 •自動轉
推薦度:
導讀vue 使用axios 數據請求第三方插件的使用教程詳解:axios 基于http客戶端的promise,面向瀏覽器和nodejs 特色 •瀏覽器端發起XMLHttpRequests請求 •node端發起http請求 •支持Promise API •監聽請求和返回 •轉化請求和返回 •取消請求 •自動轉

axios

基于http客戶端的promise,面向瀏覽器和nodejs

特色

•瀏覽器端發起XMLHttpRequests請求
•node端發起http請求
•支持Promise API
•監聽請求和返回
•轉化請求和返回
•取消請求
•自動轉化json數據
•客戶端支持抵御

安裝

使用npm:

$ npm i axiso

為了解決post默認使用的是x-www-from-urlencoded 去請求數據,導致請求參數無法傳遞到后臺,所以還需要安裝一個插件QS

$ npm install qs

一個命令全部解決

$ npm install --save axios vue-axios qs

兩種方法在vue中使用 axios

方法-:修改原型鏈

首先在 main.js 中引入 axios

import Axiso from 'axiso'

這時候如果在其它的組件中,是無法使用 axios 命令的。但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個問題

Vue.prototype.$axios= Axios

 配置好了之后就可以全局使用了

示例:在main.js使用

Get請求:

//發起一個user請求,參數為給定的ID
$axios.get('/user?ID=1234')
.then(function(respone){
 console.log(response);
})
.catch(function(error){
 console.log(error);
});

Post請求

$axios.post('/user', {
 firstName: 'Fred',
 lastName: 'Flintstone'
 })
 .then(function (response) {
 console.log(response);
 })
 .catch(function (error) {
 console.log(error);
 });

為了保證請求的數據正確,可以在main.js配置如下內容:

Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口請求地址
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情況使用
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置請求頭信息。

 那么最基本的配置已經完成了,但是還有一個問題,既然是前后端分離,那么肯定避免不了跨域請求數據的問題,接下來就是配置跨域了。

在config/index.js里面的dev里面配置如下代碼:

proxyTable: {
 '/api': {
 target: 'http://xxx.xxx.xxx.xxx:8081/',//設置你調用的接口域名和端口號 別忘了加http
 changeOrigin: true,
 pathRewrite: {
 '^/api': '/'//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'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/',//設置你調用的接口域名和端口號 別忘了加http
 changeOrigin: true,
 pathRewrite: {
 '^/api': '/'//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我 要調用'http://xxx.xxx.xxx.xxx:8081/user/add',直接寫‘/api/user/add'即可
 }
 }
 },

  但是注意了,這只是開發環境(dev)中解決了跨域問題,生產環境中真正部署到服務器上如果是非同源還是存在跨域問題.

axios攔截器的使用

當我們訪問某個地址頁面時,有時會要求我們重新登錄后再訪問該頁面,也就是身份認證失效了,如token丟失了,或者是token依然存在本地,但是卻失效了,所以單單判斷本地有沒有token值不能解決問題。此時請求時服務器返回的是401錯誤,授權出錯,也就是沒有權利訪問該頁面。

我們可以在發送所有請求之前和操作服務器響應數據之前對這種情況過濾。

// http request 請求攔截器,有token值則配置上token值
axios.interceptors.request.use(
 config => {
 if (token) { // 每次發送請求之前判斷是否存在token,如果存在,則統一在http請求的header都加上token,不用每次請求都手動添加了
 config.headers.Authorization = token;
 }
 return config;
 },
 err => {
 return Promise.reject(err);
 });
// http response 服務器響應攔截器,這里攔截401錯誤,并重新跳入登頁重新獲取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}//登錄成功后跳入瀏覽的當前頁面
 })
 }
 }
 return Promise.reject(error.response.data) 
 });

 安裝qs插件后的簡化操作

$ npm install qs
import QS from 'qs'
//axios攔截器
// 超時時間
Axios.defaults.timeout = 5000;
// http請求攔截器 請求之前的一些操作
Axios.interceptors.request.use(config => {
 if(config.method=='post'){
 config.data=QS.stringify(config.data);//防止post請求參數無法傳到后臺
 }
 return config
}, error => {
 Message.error({
 message: '加載超時'
 });
 return Promise.reject(error)
});
// http響應攔截器 請求之后的操作
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請求參數無法傳到后臺
 }</span><br>這句可以直接代替
<span style="color: rgb(255, 0, 0);">Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口請求地址
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情況使用
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置請求頭信息。</span>

<br><span style="font-size: 14pt;">vue 訪問本地json文件的數據測試配置方法<br>第一步,準備json數據<br>json文件位置:src/data/data.json<br>第二步,配置webpack.dev.conf.js 文件<br>在webpack.dev.config.js 里面添加如下代碼:<br></span>
// webpack.dev.conf.js
// 通過express導入路由
const express = require('express')
const app = express()
var appData = require('../src/data/data.json')
// json賣家數據
var seller = appData.seller
// json商品數據
var goods = appData.goods
// json評論數據
var ratings = appData.ratings
// 編寫路由
var apiRoutes = express.Router()
// 所有通過接口相關的api都會通過api這個路由導向到具體的路由
app.use('/api', apiRoutes)
//devServer下寫入如下代碼:
 before(app) {
 app.get('/api/seller', (req, res) => {
 res.json({
 errno: 0,
 data: seller
 })//接口返回json數據,上面配置的數據seller就賦值給data請求后調用
 }),
 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
// 通過express導入路由
const express = require('express')
const app = express()
var appData = require('../src/data/data.json')
// json賣家數據
var seller = appData.seller
// json商品數據
var goods = appData.goods
// json評論數據
var ratings = appData.ratings
// 編寫路由
var apiRoutes = express.Router()
// 所有通過接口相關的api都會通過api這個路由導向到具體的路由
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數據,上面配置的數據seller就賦值給data請求后調用
 }),
 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攔截器
// 超時時間
Axios.defaults.timeout = 5000;
// http請求攔截器
Axios.interceptors.request.use(config => {
 if(config.method=='post'){
 config.data=QS.stringify(config.data);//防止post請求參數無法傳到后臺
 }
 return config
}, error => {
 Message.error({
 message: '加載超時'
 });
 return Promise.reject(error)
});
// http響應攔截器
Axios.interceptors.response.use(data => {
 return data
}, error => {
 Message.error({
 message: '加載失敗'
 });
 return Promise.reject(error)
});
// 注冊一個全局自定義指令 `v-focus`
Vue.directive('focus', {
 // 當被綁定的元素插入到 DOM 中時……
 inserted: function (el) {
 // 聚焦元素
 el.focus()
 }
})
/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 components: { App },
 template: '<App/>'
})

  本地成功請求數據效果:

<span style="font-size: 14pt;"> </span> 

總結

以上所述是小編給大家介紹的vue 使用axios 數據請求第三方插件的使用教程詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

vue 使用axios 數據請求第三方插件的使用教程詳解

vue 使用axios 數據請求第三方插件的使用教程詳解:axios 基于http客戶端的promise,面向瀏覽器和nodejs 特色 •瀏覽器端發起XMLHttpRequests請求 •node端發起http請求 •支持Promise API •監聽請求和返回 •轉化請求和返回 •取消請求 •自動轉
推薦度:
標簽: VUE 插件 請求數據
  • 熱門焦點

最新推薦

猜你喜歡

熱門推薦

專題
Top
主站蜘蛛池模板: 国产成人免费视频精品一区二区 | 精品一区二区三区的国产在线观看 | 日韩 亚洲 欧美 中文 高清 | 欧美精品一区二区三区在线 | 国内精品一区二区2021在线 | 日韩成人国产精品视频 | 国产精品久久久久a影院 | 国产激情一级毛片久久久 | 亚洲欧美日韩高清一区二区一 | 欧美日韩精品一区二区三区四区 | 日韩欧美在线视频观看 | 成人精品视频在线 | 亚洲欧美天堂网 | 欧美日韩极品 | 国产一区二区三区成人久久片 | 国产视频高清在线观看 | 日韩欧美大陆 | 国产欧美久久一区二区 | 国内精品视频一区二区三区 | 欧美日韩精品一区二区三区高清视频 | 人人揉揉香蕉大青草 | 99久久精品免费国产一区二区三区 | 一久久| 99精品欧美一区二区三区综合在线 | 成人a毛片一级 | 亚洲国产成人精彩精品 | 亚洲永久精品一区二区三区 | 不卡的中文字幕 | 国产网站免费在线观看 | 国产精品高清一区二区三区不卡 | 免费看一级黄色毛片 | 亚洲欧美日韩高清一区二区一 | 日韩欧美精品 | 欧美日韩亚洲另类 | 在线视频一区二区 | 久久国产精品久久精 | 91www成人久久| 国产夜夜操 | 欧美日韩91 | 欧美 日韩 国产在线 | 天天爱夜夜操 |