1、问题:vue3中用axios请求数据时报错

Access to XMLHttpRequest at 'http://127.0.0.1/api/dash' from origin
 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 
header is present on the requested resource.

2、解决方法:
在vue.config.js中配置,配置代码如下:

devServer: {
    host: '0.0.0.0',
    port: 8080,
    open: true,
    proxy: {
      '/api': {
        target: 'http://127.0.0.1/api/', //接口域名
        changeOrigin: true,       //是否跨域
        ws: true,            //是否代理 websockets
        secure: true,          //是否https接口
        pathRewrite: {
          '^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
        }
      },
      // headers:{
      //   'Access-Control-Allow-Origin':'*'
      // } 
    }
  }


在main.ts中添加:

import { createApp } from 'vue';
import App from './App.vue';
import axios from "axios";
import VueAxios from 'vue-axios';


const app = createApp(App);
app.use(VueAxios, axios).mount('#app');


axios.defaults.baseURL = '/api/'  // api 即上面 vue.config.js 中配置的地址
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
//将axios挂载到原型对象上,vue3相比vue2有所改变,vue2这样写:Vue.prototype.$http = axios
app.config.globalProperties.$axios = axios;

在index.vue中用axios请求数据:

import { getCurrentInstance} from 'vue';
let { proxy } = getCurrentInstance();
proxy.$http.get(`dash`)
    .then(response => {
      // 处理响应数据
      console.log(response);

    })
    .catch(error => {
      // 处理请求错误
      console.log(error);
    });


再重新运行:npm run serve ,成功了!!!!!

浏览器中请求数据的接口是http://localhost:8080/api,指向http://127.0.0.1/api/

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐