// 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');
});
main.js
中配置了 Axios 的默认设置,添加了跨域请求头 Access-Control-Allow-Origin
,以便允许跨域请求。async/await
发起跨域请求,并将返回的数据绑定到组件的状态中。cors
中间件来处理跨域请求。上一篇:vue class绑定的几种方法
下一篇:vue3写法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站