Spring+React前后端分离项目中跨域问题的完美解决方案

springboot+react前后端分离项目中,跨域问题必然存在,解决方案有三种类型:
1、前端解决:
在package.json中添加如下代码:

{
  "name": "myproject1",
  "version": "0.1.0",
  "private": true,
  **"proxy": "http://localhost:9090",**
  "dependencies": {
    "antd": "^3.0.3",
    "fetch": "^1.1.0",
    "flux": "^3.1.3",
    "react": "^15.4.1",
    "react-addons-css-transition-group": "^15.6.2",
    "react-dom": "^15.4.1",
    "react-router": "^3.0.0",
    "react-scripts": "1.0.17"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "reqwest": "^2.0.5"
  }
}

缺点:由于域名部分是固定的,无法解决跨多个网站请求资源的跨域;
2.后端解决方案:
2.1、参考文章;
2.2、原理:添加SpringMVC底层实现的Web配置适配器,增加CORS相关的配置信息;

package com.spring.boot.gp4zj.webconfig;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CORSConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowedHeaders("*");
    }
}

3.3、添加代理服务器,如nginx配置,前面讲过;

你可能感兴趣的:(J2EE)