1.错误代码
类似下面这种blocked by CORS
,即CORS(Cross-Origin Resource Sharing,跨源资源共享)被限制
Access to XMLHttpRequest at 'http://localhost:9999/user/info' from origin 'http://localhost:7000' has been blocked by
CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
is present on the requested resource.
2.解决方法
重写WebMvcConfigurer(全局跨域)
package com.example.demo;
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 CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")//允许任何源发起跨域请求(使用通配符 "*")。
.allowCredentials(true)//允许请求携带身份验证信息(如cookies)。
.allowedMethods("GET", "POST", "DELETE", "PUT")//允许的HTTP方法包括GET、POST、DELETE和PUT。
.maxAge(3600);//设置预检请求的有效时间为3600秒(1小时),即在此期间内,对于相同类型的跨域请求,浏览器不会重复发送预检请求。
}
}