vue中用axios来去访问接口数据

img

img

img


vue中用axios来去访问接口数据,跨域也配置了,可是为啥出现了错误,搞不懂,求帮助

【以下回答由 GPT 生成】

我可以帮助你解决这个问题。

首先,让我们来处理跨域问题。

  1. 在你的Vue项目中安装axios:
npm install axios
  1. 创建一个axios实例来设置默认的请求配置:
import axios from 'axios';

const api = axios.create({
  baseURL: 'http://api.example.com',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
});

请注意在上面的代码中将baseURL设置为你的API的URL。

  1. 在你的Vue项目中创建一个代理配置文件vue.config.js,用于解决跨域问题。如果没有该文件,请在根目录下创建它。
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://api.example.com',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': '',
        },
      },
    },
  },
};

请将target字段的值设置为你的API的URL。

  1. 在你的Vue组件中使用axios来发起请求:
<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': ''
        }