Java后端解决前后端分离的跨域问题

解决方式:后端解决,前端不需要解决跨域问题。
方案一:

package com.markerhub.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 {
    
    
//    现在越来越多的开发使用了请后端分离,或者由于一些网站多个模块的部署,需要跨域请求。为此,使用CorsRegistry。
    @Override
//    maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

方案2

//支持跨域请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

Access-Control-Allow-Origin:* 表示允许任何域名跨域访问,由于设置存在安全隐患,建议将改成你想允许的域名。

猜你喜欢

转载自blog.csdn.net/qq_46199553/article/details/120729052