Vue3+axios跨域问题


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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值