vue的跨域问题

vue的跨域问题

*本文只针对使用vue-cli构建的项目


问题描述:

使用 Vue-cli 创建的项目,开发地址是 localhost:8080,需要访问 localhost:8888 上的接口


分析原因:

不同域名之间的访问,需要跨域才能正确请求。跨域的方法很多,通常都需要后台配置。
不过 Vue-cli 创建的项目,可以直接利用 Node.js 代理服务器,实现跨域请求。


解决方案:

1.在我们使用vue-cli构建项目时,会有我们设置跨域请求的文件。


2.在开发过程中,当跨域无法请求的时我们可以修改项目下config文件夹下的index.js中的dev:{}部分

dev: {
        env: require('./dev.env'),
        port: 8888,
        autoOpenBrowser: true,
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            '/api':{
                target:'http://47.93.173.81:8080/',
                changeOrigin:true,
                pathRewrite:{
                    '/api':''
                }
            }
        },
        // CSS Sourcemaps off by default because relative paths are "buggy"
        // with this option, according to the CSS-Loader README
        // (https://github.com/webpack/css-loader#sourcemaps)
        // In our experience, they generally work as expected,
        // just be aware of this issue when enabling this option.
        cssSourceMap: false
   }

target设置为我们需要访问的域名。


3.然后在main.js中配置全局请求路径

Vue.prototype.HOST = '/api'

4.至此,我们就可以在全局使用这个域名了,如下:

var url = this.HOST + '/teacherSide/getTreeQuestions'
this.$http.get(url).then(res => {
   this.movieList = res.data.subjects;
 },res => {
   console.info('调用失败');
 });

猜你喜欢

转载自blog.csdn.net/u014628388/article/details/77976525