How does a VuePress website use axios to request a third-party interface?

19d4a00e5e6ab07957b5e7f0328c5353.jpeg

Preface

VuePress is a pure static website generator, that is, it has no backend and is purely front-end. If you want to send an ajax request to request some third-party interfaces in VuePress, Sometimes I want to achieve some of my own goals

InVuePress, use axios to request a third-party interface. You need to install axios first, then import it, and finally use

This article includes

  • Install and use axios in VuePress, use it directly and mount it under the root instance

  • Solve cross-domain problems. When using axios to request a third-party interface in VuePress, cross-domain problems may occur

  • When using axios to request a third-party interface, how to carry parameters and complete the request?

Install axios

npm install [email protected] -S

Precautions

If an error is reported when using axios, try lowering the axios version.

Using axios within the component

Quoteaxios in a single file component, then use axios.get() and axios.post() to sendgetRequest orpostRequest

<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>

Solve cross-domain issues

If you make an ajax request in the component axios.get('http://v.juhe.cn/joke/content/text.php',{params:{key:'xxx 39;}})

此时会报错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.

Enter.vuepress/config.js, configuration file

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': ''       
             }      
          }, 
    }  
  }
};

When accessing the beginning of in the Vue component, the front end will automatically proxy to the destination. , this completes the switch to the proxy and solves the cross-domain problem in the development environment/apitarget

Some people on the Internet said that create vue.config.js in the root directory and configure the devServer configuration into vue.config.js. I tried I found that it doesn’t work. I don’t know why. Anyone who knows can tell me. Thank you

If you want to use it globallyaxios, mount it to the Vue root instance and introduce it globally. If not, use it in the componentaxiosBefore, it needed to be introduced on demand every time

In order to solve this problem, you can mount the axios object in Vue's prototype for one-time injection In this way, there areaxiosobjects under the instance component.

Globally introduce axios

Existingdocs/.vuepress/enhanceApp.jsIncoming

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

When using in the component, you only need this.$axios.get(), or this.$axios.post(). There is no need to introduce it every time before the single-file component. axiosYes

In fact, the introduction ofJquery is also similar. Anyone who wants to mount the public properties and methods under the root instance of the Vue component can do so.

Front-end and back-end development interface joint debugging and docking parameters

2023-09-13

0be2d159385162b39b4e1b7b60d94d66.jpeg

Fill out questionnaires and earn bonuses

2023-09-12

524a3649832f4345a77f684f2a6b68c8.jpeg

Implementing 3D panoramic room viewing in Vue

2023-09-11

d15e9b279eba8496045d115d552019cb.jpeg

The old lady, aunt and harvester scholar were banned

2023-09-10

4e37da2361b0b1926f91709d0060da79.jpeg

Let’s talk about sauce latte, Ruixing and Moutai join forces

2023-09-09

87c0ad82e07d0eec1e2a77ef62d694e4.jpeg

Implement automatic rotation of 3D ball in Vue

2023-09-08

338329fd30ef000bf52f64074ab3e954.jpeg

How to implement a 3D city distribution map in Vue

2023-09-07

e6c17d9eb15dbc2e6556c69fe2a24793.jpeg

4d9eac9ae2775ec97bccfa7a428dd2b8.png

(Able to draw and answer questions)

9f3221c2f01a143ced2ce7037bc3e388.png

Guess you like

Origin blog.csdn.net/wzc_coder/article/details/132929143