如何使用Vue和axios实现调用第三方插件进行数据请求的详细教程?

2026-04-10 01:381阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1553个文字,预计阅读时间需要7分钟。

如何使用Vue和axios实现调用第三方插件进行数据请求的详细教程?

Axios 是一个基于 HTTP 客户端的 Promise 库,适用于浏览器和 Node.js 环境。它具有以下特点:

- 浏览器端和 Node.js 端通用- 基于 XMLHttpRequests 发起请求- Node.js 端支持 HTTP 请求- 支持 Promise API- 监听请求和响应- 转换请求和响应- 取消请求- 自动转换 JSON 数据

axios

基于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: 'xxx.xxx.xxx.xxx:8081/',//设置你调用的接口域名和端口号 别忘了加xxx.xxx.xxx.xx:8081/user/add',直接写‘/api/user/add'即可 } }

完整代码:

dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'xxx.xxx.xxx.xxx:8081/',//设置你调用的接口域名和端口号 别忘了加xxx.xxx.xxx.xxx:8081/user/add',直接写‘/api/user/add'即可 } } },

  但是注意了,这只是开发环境(dev)中解决了跨域问题,生产环境中真正部署到服务器上如果是非同源还是存在跨域问题.

axios拦截器的使用

当我们访问某个地址页面时,有时会要求我们重新登录后再访问该页面,也就是身份认证失效了,如token丢失了,或者是token依然存在本地,但是却失效了,所以单单判断本地有没有token值不能解决问题。此时请求时服务器返回的是401错误,授权出错,也就是没有权利访问该页面。

我们可以在发送所有请求之前和操作服务器响应数据之前对这种情况过滤。

// 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(), // 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: ${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/>' })

  本地成功请求数据效果:

如何使用Vue和axios实现调用第三方插件进行数据请求的详细教程?

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

总结

以上所述是小编给大家介绍的vue 使用axios 数据请求第三方插件的使用教程详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对自由互联网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

标签:教程

本文共计1553个文字,预计阅读时间需要7分钟。

如何使用Vue和axios实现调用第三方插件进行数据请求的详细教程?

Axios 是一个基于 HTTP 客户端的 Promise 库,适用于浏览器和 Node.js 环境。它具有以下特点:

- 浏览器端和 Node.js 端通用- 基于 XMLHttpRequests 发起请求- Node.js 端支持 HTTP 请求- 支持 Promise API- 监听请求和响应- 转换请求和响应- 取消请求- 自动转换 JSON 数据

axios

基于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: 'xxx.xxx.xxx.xxx:8081/',//设置你调用的接口域名和端口号 别忘了加xxx.xxx.xxx.xx:8081/user/add',直接写‘/api/user/add'即可 } }

完整代码:

dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'xxx.xxx.xxx.xxx:8081/',//设置你调用的接口域名和端口号 别忘了加xxx.xxx.xxx.xxx:8081/user/add',直接写‘/api/user/add'即可 } } },

  但是注意了,这只是开发环境(dev)中解决了跨域问题,生产环境中真正部署到服务器上如果是非同源还是存在跨域问题.

axios拦截器的使用

当我们访问某个地址页面时,有时会要求我们重新登录后再访问该页面,也就是身份认证失效了,如token丢失了,或者是token依然存在本地,但是却失效了,所以单单判断本地有没有token值不能解决问题。此时请求时服务器返回的是401错误,授权出错,也就是没有权利访问该页面。

我们可以在发送所有请求之前和操作服务器响应数据之前对这种情况过滤。

// 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(), // 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: ${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/>' })

  本地成功请求数据效果:

如何使用Vue和axios实现调用第三方插件进行数据请求的详细教程?

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

总结

以上所述是小编给大家介绍的vue 使用axios 数据请求第三方插件的使用教程详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对自由互联网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

标签:教程