使用Ajax跨域请求时候浏览器控制台抛出错误:
Access to xMLHttpRequest at "http://192.168.test.html:200.2:8080/course/tyy"from origin "http://127.0.0.1:5500"has been blocked by coRs policy: No 'Access-Control-Allow-0rigin"header is present on the requestedresource.
在java控制器里面创建一个class,输入以下代码就可以了
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 {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://127.0.0.1:5500")//允许请求的ip地址
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(false);
}
}