当前位置:Gxlcms > 数据库问题 > 跨域问题(CORS / Access-Control-Allow-Origin)

跨域问题(CORS / Access-Control-Allow-Origin)

时间:2021-07-01 10:21:17 帮助过:3人阅读

添加响应头

在被请求资源中添加响应头信息"Access-Control-Allow-Origin:*

过滤器

在本项目中添加如下过滤器:

/**
 * 解决跨域问题
 */
public class AccessControlAllowOriginFilter implements Filter {
 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
 
     chain.doFilter(req, response);
   } 
 
   public void init(FilterConfig filterConfig) {
 
   } 
 
   public void destroy() {
 
   } 
 
}

 

注解方式

在Spring Boot中拥有大量的注解,针对跨域问题,也提供了对应的注解@CrossOrigin,使用方法如下:

import java.util.HashMap;
 
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author xcbeyond
 */
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class DemoController {
        
    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/get")
    public String get() {
        ……
    }
}

PS:本文转载自:https://blog.csdn.net/xcbeyond/article/details/84453832

跨域问题(CORS / Access-Control-Allow-Origin)

标签:共享   dom   work   conf   log   details   ola   util   额外   

人气教程排行