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.youkuaiyun.com/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.youkuaiyun.com/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.youkuaiyun.com/sdhshsjh/article/details/126680270

### 在 `vue-element-admin` 中为单个 Axios 请求设置自定义请求头 在 `vue-element-admin` 项目中,可以通过配置 Axios 实例来为特定的请求添加自定义请求头。具体实现方法如下: #### 方法一:直接在请求中指定 headers 参数 对于单次请求,可以在发起请求时直接传递 `headers` 配置项。 ```javascript import axios from &#39;axios&#39;; const response = await axios.get(&#39;/api/data&#39;, { headers: { &#39;Authorization&#39;: &#39;Bearer your_token_here&#39;, &#39;Custom-Header&#39;: &#39;custom_value&#39; } }); console.log(response.data); ``` 这种方法适用于临时性的需,在每次调用 API 的地方单独处理即可[^1]。 #### 方法二:创建独立的 Axios 实例并预设 Headers 如果某些接口都需要相同的头部信息,则可以考虑新建一个带有默认配置的新实例。 ```javascript // 创建一个新的Axios实例,并为其设定默认header属性 const customInstance = axios.create({ baseURL: process.env.VUE_APP_BASE_API, timeout: 5000, headers: {&#39;X-Custom-Header&#39;: &#39;foobar&#39;} }); export default customInstance; ``` 之后在整个应用里使用这个新的客户端来进行网络通信就可以自动携带这些额外的信息了[^2]。 #### 方法三:利用拦截器机制动态修改 Header 当需要根据不同条件灵活调整 header 值的时候,还可以借助于 Axios 提供的请求/响应拦截功能。 ```javascript axios.interceptors.request.use(config => { // 可在此处根据业务逻辑判断是否要附加token或其他认证凭证 const token = localStorage.getItem(&#39;token&#39;); if (token && config.url.includes(&#39;/specific-endpoint&#39;)) { config.headers[&#39;Authorization&#39;] = `Bearer ${token}`; } return config; }, error => Promise.reject(error)); ``` 此方式允许开发者基于上下文环境或用户状态等因素决定哪些请求应该包含特殊的 HTTP 头部字段[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西京刀客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值