vue 跨域 springCloud @CrossOrigin注解 vue中config/index.js:配置的详细理解

vue 跨域  springCloud @CrossOrigin注解

一丶什么是跨域

跨域问题来源于浏览器的同源策略,浏览器为了提高网站的安全性,在发送ajax请求时,只有在当前页面地址与请求地址的协议+域名+端口号相同时才允许访问,否则会被拦截。

协议即通信协议,比如我们现在常见的http和https,如果当前页面地址使用http协议,请求的地址使用https协议,那么这个请求就存在跨域问题。

域名即网站网址,如baidu.com,360.com存在跨域

端口号即域名对应的服务器的监听端口,这个我们一般是看不到的,因为一般服务器都使用80端口,浏览器默认为80端口,所以不需要在域名后再写出端口号。当8080端口发出的请求为80端口时,也存在跨域

当我们请求一个接口的时候,出现如:Access-Control-Allow-Origin 字眼的时候说明请求跨域了

在前后端分离后,请求数据时跨域问题出现的越来越多,如何解决呢?

二丶如何解决跨域问题

1.使用jsonp实现,网页通过script标签向服务器请求json数据,服务器受到请求后,将数据放在一个指定名字的回调函数的参数里面传给前端。

<script src="http://www.test.com/getData?callback=getData"></script>
// 向服务器test.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字

// 处理服务器返回回调函数的数据
<script type="text/javascript">
    // 服务器返回的数据会放到回调函数里面
    function getData(res){
        // 处理获得的数据
        console.log(res.data)
    }
</script>

2.使用Jquery ajax实现,

$.ajax({
  url: 'http://www.test.com:8888/getData',
  type: 'get',
  dataType: 'jsonp',  // 请求方式为jsonp
  jsonpCallback: "handleCallback",    // 自定义回调函数名
  data: {}
})

  3.在vue开发中实现跨域:

proxy中设置跨域vue -->config--> index.js

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../manage/index.html'),
    assetsRoot: path.resolve(__dirname, '../manage/'),
    assetsSubDirectory: 'static',

    assetsPublicPath: './',
    productionSourceMap: true,

    productionGzip: false,
    productionGzipExtensions: ['js', 'css']
  },
  dev: {
    env: require('./dev.env'),
    port: 8088,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        // target: 'http://10.9.65.114:8005',
        
        // target: 'http://10.9.240.3:8020',
        // DAT
        target: 'http://10.9.240.9:8020',
        // Localhost
        // target: 'http://10.9.240.14:8020',
        pathRewrite: {
          '^/api': '/'
        }
      }
    },

    cssSourceMap: false
  }
}

  在vue中使用proxy进行跨域的原理是:将域名发送给本地的服务器(启动vue项目的服务,loclahost:8080),再由本地的服务器去请求真正的服务器。

以下是我在开发vue项目中实现跨域的步骤:

  1.在proxy中设置要访问的地址,并重写/api为空的字符串,因为我们真正请求的地址是没有带/api,这个重写很重要!!!

  2.在创建axios实例的时候将baseURL设置为/api ,这时候我们的跨域就已经完成了。

  3. 假如请求的真正地址为:http://121.121.67.254:8185/core/getdata/userInfo,但我们在浏览器上会看到是这样的: http://localhost:8080/api/core/getData/userInfo ,多了个/api,但并不影响我们请求数据。

三丶自己项目用处

三丶参考:vue中config/index.js:配置的详细理解

https://www.cnblogs.com/yangguoe/p/9293892.html

https://www.cnblogs.com/lihaohua/p/12372267.html

猜你喜欢

转载自www.cnblogs.com/zytcomeon/p/13390666.html