vue-cli4.x请求跨域解决方法

1、项目根目录下新建一个vue.config.js文件,项目创建之初默认没有该文件。

2、写入配置

module.exports = {
    
    

    publicPath: '/',   //这个必须,引入静态资源需要从根路径引入,否则会找不到静态资源
    devServer: {
    
    
        port: 8080, // 访问端口
        // history模式下的url会请求到服务器端,但是服务器端并没有这一个资源文件,就会返回404,所以需要配置这一项
        historyApiFallback: {
    
    
            index: '/index.html' //与output的publicPath
        },

        proxy: {
    
    
            ['/musicApi']: {
    
    //拦截链接中有/musicApi
                target: 'https://autumnfish.cn',//API服务器的地址
                changeOrigin: true,
                pathRewrite: {
    
    
                   '^/musicApi': '' 
                }
             }
        }
    },

}

3、axios发起请求格式如下

this.$axios.get("/musicApi/search?keywords="+that.musicName).then(
        function(res){
    
    
          // 请求成功
        }
).catch(function(){
    
    
	//请求失败
})

注意:本地可以实用如上配置,如果要部署到服务器,那么如上配置就不能生效了。在服务器解决跨域问题可以使用Nginx反向代理来解决跨域问题。

Guess you like

Origin blog.csdn.net/Stand_Fast/article/details/119089198