VuePress网站如何使用axios请求第三方接口

19d4a00e5e6ab07957b5e7f0328c5353.jpeg

前言

VuePress是一个纯静态网站生成器,也就是它是无后端,纯前端的,那想要在VuePress中,发送ajax请求,请求一些第三方接口,有时想要达到自己一些目的

VuePress中,使用axios请求第三方接口,需要先安装axios,然后引入,最后使用

本文包括

  • VuePress中安装和使用axios,直接使用与挂载在根实例下使用

  • 解决跨域的问题,VuePress中使用axios请求第三方接口时,会出现跨域问题

  • 使用axios请求第三方接口时,如何携带参数,完成请求

安装axios

npm install [email protected] -S

注意事项

如果使用axios报错,则尝试降低axios版本

组件内使用axios

在单文件见组件中引用axios,然后使用axios.get()axios.post()发送get请求或post请求

<template>
    <div>
        <el-button type="primary" @click="handleBtnGetJoke" :disabled="isDisabled">请求数据</el-button>
        <el-button type="danger" @click="handleBtnClearData" v-if="aDatas.length > 0?true:false">清空数据</el-button>
        <ul v-if="aDatas.length > 0?true:false">
            <li class="joke-list" v-for="item in aDatas"
                                  :key="item.hashId">{
    
    { item.content }}
            </li>
            <div class="loading" v-if="aDatas.length > 0?true:false"> 
                <el-button size="mini"  type="primary" @click="handleBtnLoading" >加载</el-button>
            </div>
        </ul> 
    </div>
</template>

<script>
    import axios from 'axios';
    export default {
        name: 'vuepressAxios',
        data() {
            return {
               aDatas: [],
               isDisabled: false,
               page: 1,
               pagesize: 5,
            }
        },
        methods: {
            async handleBtnGetJoke() {
                this.isDisabled = true;
                const params = {
                    key: "aa1b7ad08be2a09a4e0d2d46897e2dc8",
                    page: this.page,
                    pagesize: this.pagesize,
                }
                // const response = await axios.get('/api/joke/content/text.php',{params});
                const response = await this.$axios.get('/api/joke/content/text.php',{params});
                console.log(response);
                if(response.status === 200) {
                    this.isDisabled = false;
                    this.$message.success('数据请求成功');
                    const { data } = response;
                    this.aDatas = this.aDatas.concat(data.result.data);
                }else {
                    this.$message.error('数据请求失败');
                }
               
            },

            handleBtnClearData() {
                this.aDatas = [];
            },

            handleBtnLoading() {
                this.page++;
                this.handleBtnGetJoke();
            }
        }
    }
</script>

<style lang="scss" scoped>
.joke-list {
    list-style-type: decimal;
    list-style-position: outside;
    padding: 5px 0;
    border-bottom: dashed 1px #ccc;
}

.loading {
    margin: 0 auto;
    text-align:center;
}
</style>

解决跨域问题

如果你在组件中ajax发起请求时axios.get('http://v.juhe.cn/joke/content/text.php',{params:{key:'xxx'}})

此时会报错Access to XMLHttpRequest at 'http://v.juhe.cn/joke/content/text.php?key=xxx' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

进入.vuepress/config.js,配置文件中

module.exports = {
  title: 'itclanCoder', // 博客标题
  description: 'itclanCoder,itclanCoder的技术博客,itclan', // 博客描述,利于SEO
  keywords: 'itclanCoder的技术博客, itclanCoder', // 关键字
  // ...其他省略
  devServer: {    // 添加这个devServer配置  
    proxy: {     
         '/api': {       
             target: 'http://v.juhe.cn',     // 这里填写具体的真实服务器接口地止   
             changeOrigin: true,            // 允许跨域  
             pathRewrite: {          
                '^/api': ''       
             }      
          }, 
    }  
  }
};

当在Vue组件中访问/api开头时,前端会自动的代理到target目标地止上,这样就完成了转向代理,解决了开发环境下跨域的问题的

网上有的说,在根目录下创建vue.config.jsdevServer配置配置到vue.config.js中,我试了,发现不起作用,不知道为什么,有知道的朋友可以告诉我一下,谢谢

如果想要全局进行使用axios,把它挂载到Vue根实例下,则可以全局引入,如果不这样,那在组件当中,在使用axios之前,每次都需要按需引入的

为了解决这个问题,可以,一次性注入的,将axios对象挂载在Vueprototype下的,这样,在实例组件下都是有axios对象的

全局引入axios

docs/.vuepress/enhanceApp.js中引入

import axios from 'axios'
export default ({ Vue }) => {
    Vue.prototype.$axios = axios;
}

那在组件中,使用时,只需要this.$axios.get(),或this.$axios.post(),就可以了的,无需单文件组件前每次都引入axios了的

其实,引入Jquery也是同样类似的,凡是想要挂载在Vue组件根实例下公有属性和方法,都可以这么做

前后端开发接口联调对接参数

2023-09-13

0be2d159385162b39b4e1b7b60d94d66.jpeg

填写问卷就能赚奖金

2023-09-12

524a3649832f4345a77f684f2a6b68c8.jpeg

Vue中实现全景房看图3D

2023-09-11

d15e9b279eba8496045d115d552019cb.jpeg

老太太阿姨收割机秀才被封

2023-09-10

4e37da2361b0b1926f91709d0060da79.jpeg

聊一下酱香拿铁,瑞幸与茅台强强联手

2023-09-09

87c0ad82e07d0eec1e2a77ef62d694e4.jpeg

Vue中实现3D得球自动旋转

2023-09-08

338329fd30ef000bf52f64074ab3e954.jpeg

Vue中如何实现城市3D分布图

2023-09-07

e6c17d9eb15dbc2e6556c69fe2a24793.jpeg

4d9eac9ae2775ec97bccfa7a428dd2b8.png

(能绘画,能问答)

9f3221c2f01a143ced2ce7037bc3e388.png

猜你喜欢

转载自blog.csdn.net/wzc_coder/article/details/132929143