vue3 HTTP请求中的axios示例详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue3 HTTP请求中的axios示例详解

西京刀客   2022-12-26 我要评论

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"     >{{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('请求失败');
  },
  );

工作中遇到常见问题

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:
官方: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:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们