axios跨域问题的解决(CROS错误)

记一次我遇到的跨域问题解决方法

 

项目环境:在vue-cli2.0的基础上使用axios

报错:

 (1)main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Vant,{ Swipe, SwipeItem,Lazyload } from 'vant';
import 'vant/lib/index.css'
//<1> 引入 axios
import axios from 'axios'

Vue.use(Swipe);
Vue.use(SwipeItem);
Vue.use(Vant);
Vue.use(Lazyload)

// <2> 把axios挂载到vue的原型中,在vue中每个组件都可以使用axios发送请求,
//不需要每次都 import一下 axios了,直接使用 $axios 即可
Vue.prototype.$axios = axios;


Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

(2)vue.config.js

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
        '/calendar': {
            // 此处的写法,目的是为了 将 /api 替换成 https://www.baidu.com/
            target: 'http://v.juhe.cn/calendar/day?date=2023-2-3&key=17a370865c0bb4bb428b248060b4dc4d',
            // 允许跨域
            changeOrigin: true,
            ws: true,
            pathRewrite: {
                '/calendar': ''
            }
        },
        '/weather': {
            target: 'http://t.weather.sojson.com/api/weather/city/101190101',
            // 允许跨域
            changeOrigin: true,
            ws: true,
            pathRewrite: {
                '/weather': ''
            }
        }
    }
}

})

(3)使用axios的vue文件

import axios from "axios";
methods: {
    // 万年历接口
    calendarYear() {
      // 由于 main.js 里全局定义的 axios,此处直接使用 $axios 即可
      this.$axios
        .get("/calendar", {  })
        .then((res) => {
          console.log(res, "万年历res数据");
        })
        .catch((err) => {
          console.log("获取数据失败" + err);
        });
    },
    // 天气接口
    weatherData() {
    // 好像直接写axios也可以,亲测有效
      axios
        .get("/weather")
        .then((res) => {
          console.log(res, "天气res数据");
        })
        .catch((err) => {
          console.log("获取数据失败" + err);
        });
    },
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值