【发布时间】:2021-06-15 00:06:03
【问题描述】:
我正在使用 axios 调用调用 Springboot 后端,因此即使我认为我已正确配置它,我也会收到一个 cors 错误。
我的 Vue 前端位于 localhost:3000 我的 springboot 后端位于 localhost:8080
当我在 curl 上运行它时收到这个 -
~ % curl -I http://localhost:8080/api/v1/login
HTTP/1.1 405
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Allow: POST
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 17 Mar 2021 16:08:29 GMT
WebSecurityConfig -
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:8080"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
}
CORSConfig.java -
@Configuration
public class CORSConfig implements WebMvcConfigurer {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request= (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "false");
response.setIntHeader("Access-Control-Max-Age", 3600);
filterChain.doFilter(servletRequest, servletResponse);
}
}
axios 调用 -
submit() {
let formData = new FormData();
formData.set("email", this.email)
formData.set("password", this.password)
formData.set("staySignedIn", this.staySignedIn)
axios.post("http://localhost:8080/api/v1/login", formData,
{headers: {'Content-Type': 'application/json'}})
.then(function (res) {
if (res.data.code === 200) {
this.router.push('/dashboard')
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}
【问题讨论】:
标签: spring-boot axios cors