一. 问题

前后端分离项目,将出现跨域问题。报错如下

 


二.分析问题

跨域错误源自于浏览器的同源策略,想要解决跨域首先要知道什么是同源策略?

同源策略:著名的安全策略,URL有三个基本组成部分:协议+域名或ip+端口,三个必须完全相同称之为同源,不同源的称之为跨域

URL 与 URL 对比:

http://localhost:3000/

https://localhost:3000/ 不同源:协议不同

http://localhost:3000/

http://127.0.0.1:3000/ 不同源:域名或ip不同

http://localhost:3000/

http://localhost:3001/ 不同源:端口不同

http://localhost:3000/

http://localhost:3000/ 同源

http://127.0.0.1:3000/

http://127.0.0.1:3000/ 同源

注意:同源策略不是服务器行为,而是浏览器的行为,服务器会正常响应请求,但是如果不同源会被浏览器拦截

 

三.解决问题。

  1.vue配置代理服务器

(1)在vue.config.js文件中  (切记:修改后需要重启脚手架项目)

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      //Rev 0002. vue设置代理处理跨域问题 自定义请求的开头,使用代理方式处理/proxyServer开头的请求.
      "/proxyServer": {
        //Rev 0002. 往哪个服务器发请求
        target: "http://localhost:8181",
        pathRewrite: {
          "^/proxyServer": "",
        },
      },
      //Rev 0002. 如果有其他网址也需要跨域则继续配置
    },
  }
})

  

(2)配置URL根路径

axios.defaults.baseURL = '/proxyServer/'

   

(3)发送网络请求

this.$http.post('/admin/login')

 

2.使用 @CrossOrigin 注解可以轻松的实现跨域,此注解既可以修饰类,也可以修饰方法。当修饰类时,表示此类中的所有接口都可以跨域;当修饰方法时,表示此方法可以跨域;

@RestController
@CrossOrigin(origins = "*")
public class TestController {
    @RequestMapping("/test")
    public HashMap<String, Object> test() {
        return new HashMap<String, Object>() {{
            put("state", 200);
            put("data", "success");
            put("msg", "");
        }};
    }
}

 

 

3.通过配置文件跨域

接下来我们通过设置配置文件的方式就可以实现全局跨域了,它的实现步骤如下:

  1. 创建一个新配置文件;
  2. 添加 @Configuration 注解,实现 WebMvcConfigurer 接口;
  3. 重写 addCorsMappings 方法,设置允许跨域的代码。
/*
 * Rev 0000,解决vue跨域问题.
 */
@Configuration
public class CrosSconfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
      添加映射路径
        registry.addMapping("/**")
                // 允许跨域的域名或IP,星号代表允许所有
                .allowedOrigins("*")
                // 请求允许的方法,如:GET, POST, PUT, DELETE等
                .allowedMethods("*")
                // 预检间隔时间
                .maxAge(168000)
                // 允许头部设置
                .allowedHeaders("*");
    }
}

 

posted on 2023-11-23 12:57  代码少年_夕阳  阅读(70)  评论(0编辑  收藏  举报