前后端分别解决跨域问题 CORS错误

一、前端:配置nginx

# 跨域配置
location ^~ /api/ {
    proxy_pass http://127.0.0.1:8080/api/;
    add_header 'Access-Control-Allow-Origin' $http_origin;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers '*';
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Origin' $http_origin;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }
}

二、后端处理的看这

方式①:添加 web 全局请求拦截器

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                //当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
                .allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }
}

方式②:配置 @CrossOrigin 注解

package com.arhorchin.securitit.webannotations;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Securitit.
 * @note 演示@CrossOrigin注解使用方法.
 */
@Controller
@RequestMapping("/WebAnnotations")
public class CrossOriginController {

    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(CrossOriginController.class);

    /**
     * 未使用@CrossOrigin.
     */
    @ResponseBody
    @RequestMapping(
            value = "/UnCrossOrigin.do",
            method = RequestMethod.GET)
    public String unCrossOrigin(@RequestHeader Map requestHeaderMap) throws Exception {
        logger.info("@CrossOrigin use default value.");
        return "@CrossOrigin use default value.";
    }
    
    /**
     * 使用默认值的@CrossOrigin.
     */
    @ResponseBody
    @RequestMapping(
            value = "/CrossOrigin.do",
            method = RequestMethod.GET)
    @CrossOrigin
    public String crossOrigin(@RequestHeader Map requestHeaderMap) throws Exception {
        logger.info("@CrossOrigin use default value.");
        return "@CrossOrigin use default value.";
    }
    
    /**
     * 指定origins属性的@CrossOrigin.
     */
    @ResponseBody
    @RequestMapping(
            value = "/CrossOriginOrigins.do",
            method = RequestMethod.GET)
    @CrossOrigin(origins="http://localhost:9299")
    public String crossOriginOrigins(@RequestHeader Map requestHeaderMap) throws Exception {
        logger.info("@CrossOrigin with origins.");
        return "@CrossOrigin with origins.";
    }
    
    /**
     * 指定origins、allowedHeaders、exposedHeaders、allowCredentials属性的@CrossOrigin.
     */
    @ResponseBody
    @RequestMapping(
            value = "/CrossOriginOriginsAllowCredentials.do",
            method = RequestMethod.GET)
    @CrossOrigin(origins="http://localhost:9299", allowCredentials="true")
    public String crossOriginAllowedHeadersExposedHeadersAllowCredentials(@RequestHeader Map requestHeaderMap) throws Exception {
        logger.info("@CrossOrigin with origins、allowedHeaders、exposedHeaders、allowCredentials.");
        return "@CrossOrigin with origins、allowedHeaders、exposedHeaders、allowCredentials.";
    }

}

你可能感兴趣的:(前端,nginx,java)