vue-cli3以上框架解决跨域问题

事实上,3以上的版本安装好以后没有主配置文件,它不像2的版本有专门的config文件夹可以处理配置,所以我们需要新建vue.config.js  【默认情况下,3以上的版本可以直接识别这个js文件,把它当做自己的配置文件】

步骤如下:

1、在项目框架的根目录下新建文件:vue.config.js

2、重启项目,这样的话新建的文件就可以被识别了

3、给新建的文件内添加解决跨域的代码部分

module.exports = {
    outputDir: 'serve',   //build输出目录
    assetsDir: 'assets', //静态资源目录(js, css, img)
    lintOnSave: false, //是否开启eslint
    devServer: {
        open: true, //是否自动弹出浏览器页面
        host: "localhost", 
        port: '8081', 
        https: false,   //是否使用https协议
        hotOnly: false, //是否开启热更新
        proxy: {
             '/api': {
                target: 'http://www.1707laravel.com/api', //API服务器的地址
                ws: true,  //代理websockets
                changeOrigin: true, // 虚拟的站点需要更管origin
                pathRewrite: {   //重写路径 比如'/api/aaa/ccc'重写为'/aaa/ccc'
                    '^/api': ''
                }
            }
        }
    }
}

配置好以后就可以执行请求了,例如post请求是:

this.$axios.post('/api/register',{
     name:this.user_name,
     email:this.user_email,
     pwd:this.user_pwd,
     rpwd:this.user_rpwd,
     phone:this.user_phone,
     sex:this.user_sex
 })
  .then(function (res) {
      console.log(res);
  })

猜你喜欢

转载自www.cnblogs.com/jiangshiguo/p/12122120.html