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

vue axios 跨域

作者:热血震荡   发布日期:2026-04-10   浏览:14

// Vue 项目中使用 Axios 处理跨域请求的示例代码

// 1. 安装 Axios
// npm install axios

// 2. 在 main.js 或者需要的地方引入 Axios
import axios from 'axios';

// 3. 配置 Axios 默认选项,包括跨域请求时携带凭证(如 Cookies)
axios.defaults.withCredentials = true;

// 4. 创建一个 Axios 实例,配置 baseURL 和其他跨域相关设置
const instance = axios.create({
  baseURL: 'https://api.example.com', // 替换为你的 API 基础 URL
  timeout: 5000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// 5. 处理跨域请求的拦截器
instance.interceptors.request.use(
  config => {
    // 可以在这里添加一些通用的请求头,比如 Token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    if (error.response) {
      // 根据不同的 HTTP 状态码做不同处理
      switch (error.response.status) {
        case 401:
          // 未授权,可能是 Token 过期或无效
          console.error('Unauthorized');
          break;
        case 403:
          // 禁止访问
          console.error('Forbidden');
          break;
        case 404:
          // 资源未找到
          console.error('Not Found');
          break;
        case 500:
          // 服务器内部错误
          console.error('Internal Server Error');
          break;
        default:
          console.error('Something went wrong');
      }
    }
    return Promise.reject(error);
  }
);

// 6. 使用实例发送请求
export function fetchData() {
  return instance.get('/data'); // 替换为实际的 API 路径
}

// 7. 在组件中使用
import { fetchData } from './api'; // 假设 fetchData 函数在 api.js 文件中定义

export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    async loadData() {
      try {
        this.data = await fetchData();
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    },
  },
  created() {
    this.loadData();
  },
};

解释说明:

  • Axios 默认配置:通过 axios.defaults.withCredentials = true 允许跨域请求时携带凭证(如 Cookies)。
  • Axios 实例:创建了一个 Axios 实例,并设置了 baseURL 和超时时间等配置。
  • 请求和响应拦截器:用于在请求发送前和响应接收后进行处理,例如添加 Token 或处理错误状态码。
  • 发送请求:通过 instance.get() 发送 GET 请求,可以替换为 POST、PUT 等其他 HTTP 方法。
  • 组件中使用:展示了如何在 Vue 组件中调用封装好的请求函数,并处理异步数据。

上一篇:vue项目运行命令

下一篇:vue section

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

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

Laravel 中文站