【Nginx、SpringBoot】解决跨域问题,nginx.conf中的配置,以及springboot的配置

Nginx

CORS(Cross-Origin Resource Sharing)跨域资源共享

允许浏览器向跨Origin(源地址)的服务器发起js(异步)请求获取响应

实现跨域的形式:Jsonp(的形式获取数据)、SpringBoot Cros、Nginx

server {
        listen       80;  #监听的端口
        server_name  localhost; #域名
        
       #允许跨域请求的域,*代表所有
       add_header 'Access-Control-Allow-Origin' *;
       #允许带上cookie请求
       add_header 'Access-Control-Allow-Credentials' 'true';
       #允许请求的方法,比如GET/POST/PUT/DELETE
       add_header 'Access-Control-Allow-Methods' *;
       #允许请求的header
       add_header 'Access-Control-Allow-Headers' *;
        
        location /{
             root html;
             index index.html;
        }
}

SpringBoot设置跨域配置实现前后端调联

设置是否发送cookie信息

前端:
//是否要携带凭证信息
axios.defaults.withCredentials = true

后端配置:
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);

此时前后端都可以拿到cookie

配置类

前端的接口服务地址写后端开发的地址,后端配置前端的调用端地址

后端配置实现:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 实现前后端联调的跨域配置
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        //添加cors配置信息
        CorsConfiguration config = new CorsConfiguration();
        //添加允许的跨域内容,也就是前端的调用端
        config.addAllowedOrigin("http://localhost");
        //config.addAllowedOriginPattern("http://localhost");

        //凭证码,是否发送cookie信息
        config.setAllowCredentials(true);

        //设置允许请求的方式
        config.addAllowedMethod("*");

        //设置允许的header   前后端的交互信息,可以放在后端中
        config.addAllowedHeader("*");

        //为url添加映射路径(也就是允许前后端调联的url)
        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**", config);

        //返回重新定义好的corsSource
        return new CorsFilter(corsSource);
    }
}

除了写配置进行全局跨域,还可以在个别controller上设置

@CrossOrigin(origins = "http://localhost",allowedHeaders = "*",methods = {},allowCredentials = "true")

你可能感兴趣的:(Nginx,Java,nginx,spring,boot,java)