【以下回答由 GPT 生成】
我可以帮助你解决这个问题。
首先,让我们来处理跨域问题。
npm install axios
import axios from 'axios';
const api = axios.create({
baseURL: 'http://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
},
});
请注意在上面的代码中将baseURL
设置为你的API的URL。
vue.config.js
,用于解决跨域问题。如果没有该文件,请在根目录下创建它。module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://api.example.com',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': '',
},
},
},
},
};
请将target
字段的值设置为你的API的URL。
<template>
<div>
<button @click="getData">获取数据</button>
<div>{{ data }}</div>
</div>
</template>
<script>
import api from './api';
export default {
data() {
return {
data: '',
};
},
methods: {
async getData() {
try {
const response = await api.get('/api/data');
this.data = response.data;
} catch (error) {
console.error(error);
}
},
},
};
</script>
在上面的代码中,我们首先导入了我们之前创建的axios实例,并通过api.get('/api/data')
发送一个GET请求来获取数据。接下来,我们将响应的数据保存到data
变量中,并在组件中进行展示。
这样,你就可以在Vue项目中使用axios访问接口数据,并且解决了跨域问题。
如果你对以上解决方案中的步骤有任何疑问,请随时提问。
【相关推荐】
404表示找不到这个接口
pathRewrite: {
'^/api': ''
}