vue 开发模式跨域解决方案与代理服务器配置


vue 开发模式跨域解决方案与代理服务器配置

跨域:在浏览器里面域名,端口,ip地址,协议,有任何一项不同,则跨域

处理跨域的方式:

jsonp(只能处理get请求),

cors(后端开启),

代理服务器

在项目目录下创建vue.config.js.将代理服务器配置放在里面:

目前前端页面的请求地址为:http://localhost:8080

后端接口地址为:http://localhost:3000

直接发送请求会发生跨域报错

这个时候就通过前端请求本地服务器代理,然后经过代理请求后台地址实现数据交互

基本用法:

module.exports = {
  devServer: {
  host: 'localhost',
  port: 8080, //本地服务器 proxy: {
'/api': {
      target:'http://localhost:3000', //要请求的后台地址
      changeOrigin:true //是否开启跨域
} } }; 请求到 /api/xxx 现在会被代理到请求 http://localhost:3000/api/xxx, 例如 /api/user 现在会被代理到请求 http://localhost:3000/api/user

代理多个路径时:

module.exports = {
  devServer: {
    proxy: [{
      context: ['/auth', '/api'],
      target: 'http://localhost:3000',
    }]
  }
};

如果你想要代码多个路径代理到同一个target下, 你可以使用由一个或多个「具有 context 属性的对象」构成的数组:

去掉api前缀:

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'^/api' : ''}
      }
    }
  }
};
//此时浏览器f12的请求接口会显示是http://localhost:8080/api/user,但是通过代理真实请求地址是 http://localhost:3000/user

忽视https安全提示

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'https://other-server.example.com',
        secure: false
      }
    }
  }
};

默认情况下,不接受运行在 HTTPS 上,且使用了无效证书的后端服务器。如果你想要接受,只要设置 secure: false 就行。修改配置如下:

自定义规则

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        bypass: function(req, res, proxyOptions) {
          if (req.headers.accept.indexOf('html') !== -1) {
            console.log('Skipping proxy for browser request.');
            return '/index.html';
          }
        }
      }
    }
  }  
};
有时你不想代理所有的请求。可以基于一个函数的返回值绕过代理。
在函数中你可以访问请求体、响应体和代理选项。必须返回 false 或路径,来跳过代理请求。

例如:对于浏览器请求,你想要提供一个 HTML 页面,但是对于 API 请求则保持代理。你可以这样做:

跨域

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      }
    }
  }
};
上面的参数列表中有一个changeOrigin参数, 是一个布尔值, 设置为true, 本地就会虚拟一个服务器接收你的请求并代你发送该请求,

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM