spring boot提供了两种跨域配置方式
1.全局跨域
2.局部跨域

全局跨域

package com.tons.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有mapping路径
                .allowedOriginPatterns("*") // 所有域 spring-boot 2.4.0及以下使用.allowedOrigins("*")
                .allowedMethods("POST","GET","PUT","DELETE","OPTIONS") // 请求方式
                .allowedHeaders("*") // 所有方法头
                .maxAge(168000) // 等待间隔时间(时间过了则需再次认证)
                .allowCredentials(true); // cookie
    }
}

局部跨域。使用CrossOrigin注解,可修饰类或者方法。

@PostMapping("/log")
@ResponseBody
@CrossOrigin
public String logPost(@RequestBody JSONObject json, HttpSession session) {
    String username = json.getString("username");
    String password = json.getString("password");
    User user = userService.getUserById(username, password);
    if (user == null) return RestResult.Error("账号或者密码错误!");
    session.setAttribute("user", user);
    return RestResult.OK(UserTokenUtils.encodeUserToKen(user));
}

需要注意的是既是后端开启跨域并允许携带cookie,但是前端每次访问后端cookie还是会不断变化。导致HttpSession无法使用
如果想使用HttpSession(后端做无状态服务器,就不用HttpSession。转而使用JWT技术),就需要
1.每次请求携带cookie

// 这是ajax请求使用axios.js
axios.defaults.withCredentials = true // axios发送请求带上cookie,有cookie就有session_id

2.设置反向代理
开发阶段 vue-cli

devServer: {
  port: 8080,
  // 设置代理
  proxy: {
      // 替换了axios请求中的/api
    '/api': {
      // 代理地址,这里设置的地址会代替axios中设置的baseURL
      target: 'http://192.168.100.213:8088/',
      // 如果接口跨域,需要进行这个参数配置
      changeOrigin: true,
      ws: true,
      pathRewrite: {
        '^/api': ''
      }
    }
  }
}

生产阶段 ngnix

server {
    listen       80;
    server_name  localhost;
    location / {
    root   html;
    index  index.html index.htm;
    }
    # 配置代理
    location /api/ {
    proxy_pass          http://192.168.100.159:8088/;
    proxy_set_header        Host 127.0.0.1;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。