Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 axios 跨域

作者:末世修罗   发布日期:2026-01-26   浏览:85

// main.js

import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';

// 创建一个 axios 实例
const instance = axios.create({
  baseURL: 'https://api.example.com', // 设置基础 URL
  timeout: 5000, // 请求超时时间
  withCredentials: true, // 允许跨域请求携带凭证(如 cookies)
});

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response.data;
  },
  error => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

// 挂载到 Vue 实例上,方便全局使用
createApp(App).config.globalProperties.$axios = instance;

export default instance;

// 使用示例 (在组件中)
<template>
  <div>
    <button @click="fetchData">获取数据</button>
    <pre>{{ data }}</pre>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    async fetchData() {
      try {
        const response = await this.$axios.get('/endpoint');
        this.data = response;
      } catch (error) {
        console.error('There was an error fetching the data!', error);
      }
    },
  },
};
</script>

解释说明:

  1. 创建 Axios 实例:我们通过 axios.create 创建了一个自定义的 Axios 实例,并设置了基础 URL、超时时间和是否允许携带凭证。
  2. 请求和响应拦截器:我们添加了请求和响应拦截器,以便在请求发送前或响应接收后进行一些处理。例如,可以在请求拦截器中添加认证头信息,在响应拦截器中统一处理错误。
  3. 挂载到 Vue 实例:我们将自定义的 Axios 实例挂载到 Vue 的全局属性上,这样可以在任何组件中通过 this.$axios 访问它。
  4. 使用示例:在组件中展示了如何调用这个 Axios 实例来发起 HTTP 请求,并处理响应数据或错误。

如果你只需要简单的跨域配置,确保服务器端正确设置了 CORS 头信息(如 Access-Control-Allow-Origin),客户端这边通常不需要额外配置。

上一篇:vue get请求传递参数

下一篇:vue 生成uuid

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

vue3组件传值的方式

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站