vue3-HTTP请求之axios、(Axios顺序请求)一个Axios请求参数依赖于另一个Axios请求返回值

vue3-HTTP请求

背景

vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现。
axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。

axios

官网: https://axios-http.com/
github:https://github.com/axios/axios

Axios 是一个简单的基于 promise 的 HTTP 客户端,适用于浏览器和 node.js。Axios 在具有非常可扩展的接口的小包中提供了一个简单易用的库。

安装axios并引入

安装:
npm的方式:

npm install axios --save

引入,【在哪里使用,就在哪里引入】

import axios from 'axios';

使用demo:
main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
    
    
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
    <div>
        <div v-if="!repositoryUrl">loading...</div>
        <div v-else>most star repository is <a :href="repositoryUrl" rel="external nofollow"  rel="external nofollow" >{
    
    {
    
    repositoryName}}</a></div>
    </div>
    <!--App -->
</template>

<script>
    import axios from 'axios';
    
    export default {
    
    
        data() {
    
    
            return {
    
    
                repositoryUrl : '',
                repositoryName : ''
            }
        },
        
        mounted() {
    
    
            // 发ajax请求,用以获取数据,此处地址意思是查询 github中 vue 星数最高的项目
            const url = 'https://api.github.com/search/repositories?q=vue&sort=stars';
            
            axios.get(url).then(
                response => {
    
    
                    const result = response.data.items[0];
                    console.log(result)
                    this.repositoryUrl = result.html_url;
                    this.repositoryName = result.name;
                }
            ).catch(
                response => {
    
    
                    alert('请求失败');
                },
            );
        }
    }
</script>

<style>

</style>

axios POST提交数据

Content-Type: application/json

const url = '/api/v1/web3/url/list_by_category';

let data = {
    
    "category":"tools"};

axios.post(url,data).then(
  response => {
    
    
    const result = response.data.data;
    console.log(result)
    this.repositoryName = result.name;
    this.web3_urls = result


  }).catch(response => {
    
    
    alert('请求失败');
  },
  );

(Axios顺序请求)axios是一种异步请求方法,需要用await关键词修饰,等到获取到返回值后再执行后面的代码。在使用await时,需要再function前添加async关键词。

一般调用axios接口都是这样的格式。

const url = '/api/v1/web3/url/list_by_category';

let data = {
    
    "category":"tools"};

axios.post(url,data).then(
  response => {
    
    
    const result = response.data.data;
    console.log(result)
    this.repositoryName = result.name;
    this.web3_urls = result


  }).catch(response => {
    
    
    alert('请求失败');
  },
  );

这样的格式要想获取到返回值的话,就要将代码都写在then中,阅读代码的时候不是很清晰。

思路:axios是一种异步请求方法,需要用await关键词修饰,等到获取到返回值后再执行后面的代码。

先说一下async(异步的)关键字的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。然后异步方法内的需要等待执行的语句前面需要加上await。

es6新增-async函数(异步编程的最终解决方案)
参考URL: https://blog.csdn.net/m0_65912225/article/details/126134442

async函数 + await关键字 + Promise 三者配合使用

需求:完成做菜过程,每个环节的时间不等

function doDish(step){
    
    

        return new Promis((resolve)=>{
    
    

                setTimeout(()=>{
    
    

                        resolve(step)

                },2000*Math.random())  // Math.random()是一个0~1的随机数

        })

}

async function f(){
    
    

        await step1 = doDish("买菜")

        console.log(step1)

        await step1 = doDish("洗菜")

        console.log(step1)

        await step1 = doDish("切菜")

        console.log(step1)

        await step1 = doDish("炒菜")

        console.log(step1)

        console.log(“结束”)

}

console.log(111)

f()

console.log(222)

输出:111=>222=>{买菜,洗菜,切菜,炒菜,结束}

注:async函数对内同步,对外异步

工作中遇到常见问题

has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

cors阻止了你请求的资源(跨域问题)

解决方案:
在vue3.0中解决跨域首先要配置vue.config.js(在根目录下创建vue.config.js、跟package.json同级的地方)
vue.config.js

在vue.config.js中加入以下代码

module.exports = {
    
    
    devServer: {
    
    
        proxy: {
    
    
            '/api': {
    
    
                target: 'https://www.xxx.com/', //接口域名
                changeOrigin: true,             //是否跨域
                ws: true,                       //是否代理 websockets
                secure: true,                   //是否https接口
                pathRewrite: {
    
                      //路径重置
                    '^/api': ''
                }
            }
        }
    }
};

我用的vite,参考
vue3(vite)设置代理,封装axios,api解耦
参考URL: https://blog.csdn.net/sdhshsjh/article/details/126680270
官方:https://vitejs.dev/config/server-options.html

我们修改的是vite.config.js,内容如下,核心就是加入了 server–> proxy字段:

import {
    
     fileURLToPath, URL } from 'node:url'

import {
    
     defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    
    
  plugins: [vue()],
  resolve: {
    
    
    alias: {
    
    
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    
    
    proxy: {
    
    
      '/api': {
    
    
          target: 'http://127.0.0.1:8000/', //接口域名
          changeOrigin: true,             //是否跨域
          ws: false,                       //是否代理 websockets
          secure: false,                   //是否https接口
          pathRewrite: {
    
                      //路径重置
              '^/api': ''
          }
      }
    }
  }
})

参考

vue3(vite)设置代理,封装axios,api解耦
参考URL: https://blog.csdn.net/sdhshsjh/article/details/126680270

猜你喜欢

转载自blog.csdn.net/inthat/article/details/128438258