Vue中跨域问题解决方案1

我们需要配置代理。代理可以解决的原因:因为客户端请求服务端的数据是存在跨域问题的,而服务器和服务器之间可以相互请求数据,是没有跨域的概念(如果服务器没有设置禁止跨域的权限问题),也就是说,我们可以配置一个代理的服务器可以请求另一个服务器中的数据,然后把请求出来的数据返回到我们的代理服务器中,代理服务器再返回数据给我们的客户端,这样我们就可以实现跨域访问数据。

报错如下:

 解决方案如下:

1. 在项目根目录新建vue.config.js文件

2. 配置代理

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:4000', //对应自己的接口
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

3. 在main.js文件,配置一下axios.defaults.baseURL = '/api' 这样就可以保证动态的匹配生产和开发环境的定义前缀了,代码如下:

/*
入口JS
*/
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'  //关键代码
Vue.config.productionTip = false

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

4. 在组件中使用axios请求数据

<template>
 
</template>

<script>
    import FooterGuide from './components/FooterGuide/FooterGuide.vue'
    export default {
        created() {
            const url = '/index_category'
            this.$axios.get(url).then(res => {
                console.log(res)
            })
        },
    }
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>

5. 重新启动项目之后,已经解决了跨域问题。切记...

原文地址:https://www.cnblogs.com/hb88/p/12899909.html