解决No Access-Control-Allow-Origin header is present on the requested resource问题

今天前端突然找到我,说让我解决跨域问题,我一脸懵逼,我以前接口也是这么写都没有跨域问题,现在怎么有了,他给我的错误截图如下:
解决No Access-Control-Allow-Origin header is present on the requested resource问题_第1张图片
好吧,第一次遇到,找了很久,找到一个最简单的方法:
如果是springboot项目,在controller上加@CrossOrigin即可解决:
解决No Access-Control-Allow-Origin header is present on the requested resource问题_第2张图片
当然,也可以在具体方法上面加,就看你想划分的粒度大小了。
上面是基于类或者方法来控制,也可以整个工程全局配置,配置代码如下:

package config;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.TimeZone;

/**
 * 全局跨域配置
 * 
 * @author : lgs
 */
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateFormatter dateFormatter = new DateFormatter("yyyy-MM-dd HH:mm:ss");
        dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        registry.addFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                .maxAge(1000);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

如果不是springboot工程,可以参考:https://blog.csdn.net/dear_little_bear/article/details/83999391
对于@CrossOrigin的理解可以参考:https://www.cnblogs.com/mmzs/p/9167743.html

你可能感兴趣的:(错误记录)