SpringBoot+Vue前后端分离之Cors解决方案

做毕设的时候发现了这个问题,跨域问题还是比较常见的。

一、跨域问题发生的情况?

  1. 域名不同

  2. 域名相同端口不同

  3. 域名和端口都不相同

二、解决方法

1、Vue项目配置代理解决

  • (基于vue-cli2.0的项目)

    打开config/index.js,在proxyTable中添写如下代码,具体配置如下:

    proxyTable: {
    '/': {
      //配置请求转发,需要跨域的API地址
      target: 'http://localhost:8080/',
      changeOrigin: true,
      secure:false,
      //路径重写
      pathRewrite: {
        '^/': ''
      }
    },
  },
  • (基于vue-cli3.0的项目)

    在项目根目录创建vue.config.js,具体配置如下:

let proxyObj = {};

proxyObj['/'] = {
  target: 'http://localhost:8080/',
  changeOrigin: true,
  pathRewrite: {
      '^/': ''
  }
}
module.exports = {
  devServer: {
      /* 项目启动自动在浏览器打开 */
      open: true,
      host: 'localhost',
      port: 80,
      proxy: proxyObj,
  },
}
  • 局限: 以上配置仅限在本地开发环境中使用

Webpack配置官方教程:

 

 

tips: [https://webpack.docschina.org/configuration/dev-server/#devserver-proxy]

2、SpringBoot后端配置

作为一个后端攻城狮,当然考虑的是从后端解决啦

  • 在需要跨域的Controller上或方法上添加@CrossOrigin

@RestController
@RequestMapping("/authorization")
@CrossOrigin(value = "http://localhost:80")
public class AuthorizationInfoController {

  private final IAuthorizationInfoService authorizationInfoService;

  @Autowired
  public AuthorizationInfoController(IAuthorizationInfoService authorizationInfoService) {
      this.authorizationInfoService = authorizationInfoService;
  }

  @GetMapping("/{id}")
  @CrossOrigin(value = "http://localhost:80")
  public ResponseEntity<AuthorizationInfo> getAuthorizationInfoById(@PathVariable("id") Integer id){
      AuthorizationInfo authorizationInfo = authorizationInfoService.getAuthorizationInfoById(id);
      return ResponseEntity.ok(authorizationInfo);
  }
}
  • 在Spring Boot中,其实可以通过全局配置解决这个问题,全局配置只需要在配置类中重写addCorsMappings方法即可,如下:

package cn.waggag.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* @description: 配置跨域
* @author: waggag
* @Date: 2020/4/1 0:19
* @Company: http://waggag.cn/
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping("/**")   //所有方法都做处理跨域
              .allowedOrigins("http://localhost:80") //允许跨域的请求头
              .allowedMethods("*") //润许通过地请求方法
              .allowedHeaders("*"); //允许的请求头
  }
}

tips: 当然,本人更倾向于后端解决问题!!!

3、允许跨域存在的安全问题


CSRF(Cross-site request forgery),中文名称:跨站请求伪造,也被称为:one click attack/session riding,缩写为:CSRF/XSRF,我们跨域方便了,但是会遭受CSRF攻击,其实CSRF攻击就是说攻击者盗用了你的身份,以你的名义发送恶意请求。


 

 

 

posted @ 2020-04-01 00:52  王港  阅读(552)  评论(0)    收藏  举报