springboot跨域,错误:CORS 头缺少 ‘Access-Control-Allow-Origin‘

  • Post author:
  • Post category:其他




错误:已拦截跨源请求:同源策略禁止读取位于 http://localhost:9000/test 的远程资源。(原因:CORS 头缺少 ‘Access-Control-Allow-Origin’)。

在这里插入图片描述



解决方式:因为没有配置跨域所以出现这个错误

具体解决办法:注释掉的也是跨域方法,但是我用的不能解决我的问题,第二种是可以解决我的问题的。

在这里插入图片描述

package com.example.springplay.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//跨域配置类:配置跨域请求
@Configuration //声明全局配置类
public class WebConfig extends WebMvcConfigurerAdapter {
//第一种:
    //  @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        /*
//        * 1:访问路径
//        * 2:请求来源
//        * 3:请求方法
//        * 4:允许携带tocken
//        * 5:最大响应时间
//        *
//        * */
//
//        registry.addMapping("/**")
//                .allowedOrigins("Http:localhost:8080","null")
//                .allowedHeaders("GET","POST","PUT","OPTIONS","DELETE")
//                .allowCredentials(true)
//                .maxAge(3600);
//
//    }
//第二种:
    @Override
    public  void  addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(30*1000);
    }

}


在这里插入图片描述



版权声明:本文为qq_44835285原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。