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

vue跨域访问接口

作者:狂神战天   发布日期:2025-03-25   浏览:63

// Vue 跨域访问接口示例代码

// 1. 在 main.js 中配置 axios 默认设置,添加跨域请求头
import axios from 'axios'
import Vue from 'vue'

Vue.prototype.$axios = axios

// 设置默认的请求头,允许跨域
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

// 2. 在组件中发起跨域请求
<template>
  <div>
    <button @click="fetchData">获取数据</button>
    <p>{{ data }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null
    };
  },
  methods: {
    async fetchData() {
      try {
        // 发起跨域请求
        const response = await this.$axios.get('https://example.com/api/data');
        this.data = response.data;
      } catch (error) {
        console.error('There was an error fetching the data!', error);
      }
    }
  }
};
</script>

// 3. 如果后端支持 CORS(跨域资源共享),则需要在后端配置响应头
// 例如,在 Express.js 中配置 CORS
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/api/data', (req, res) => {
  res.json({ message: 'This is cross-origin data' });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

解释说明:

  1. Axios 配置:在 main.js 中配置了 Axios 的默认设置,添加了跨域请求头 Access-Control-Allow-Origin,以便允许跨域请求。
  2. 组件中的请求:在 Vue 组件中使用 async/await 发起跨域请求,并将返回的数据绑定到组件的状态中。
  3. 后端配置:如果后端支持 CORS,需要在后端配置响应头。这里以 Express.js 为例,使用 cors 中间件来处理跨域请求。

上一篇:vue class绑定的几种方法

下一篇:vue3写法

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

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

Laravel 中文站