我在spring boot 3.1
和spring security 6.1
之间完成了后端工作
我已经使用spring security
和各种控制器配置了登录.当我从Postman调用我的后端时,我没有任何问题,但当我通过ajax
时,我在浏览器控制台中收到CORS错误.我try 将配置设置为CORS
,但它不适用于我,默认设置spring
也不起作用.有什么主意吗?我把我的班级图片放在网上,以防它们对我有帮助.
类CorsConfig
package com.pms.pmsBack.config;
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("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
类SpringSecurityConfig
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http
.csrf(csrf -> csrf.disable())
.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilter(new JwtAuthenticationFilter(authenticationConfiguration.getAuthenticationManager()))
.addFilter(new JwtValidationFilter(authenticationConfiguration.getAuthenticationManager()))
.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests.requestMatchers(HttpMethod.POST, "/login")
.permitAll()
.anyRequest()
.authenticated()
);
return http.build();
}
If this is not enough, I will be attentive to the answers to add more information. Thank you so much
Axios示例:
const respuesta = await fetch('http://localhost:8080/login', data)
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Error in Request');
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});