java 对XMLHttpRequest的访问已被CORS策略阻止,请求的资源上不存在“Access-Control-Allow-Origin”标头,React[重复]

ycl3bljg  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(209)

此问题已在此处有答案

CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource(9个回答)
7小时前关闭
我用Sping Boot 做了一个API。我还实现了Spring Security。我有一个登录控制器:

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/login")
public class LoginController {
private final UserService userService;
public LoginController(UserService userService){
    this.userService = userService;
}

@PostMapping("")
public ResponseEntity login(@RequestBody AuthDTO auth){

    return ResponseEntity.status(HttpStatus.OK).body(userService.findByNameAndPassword(auth));
 }
}

在我的SecurityConfig文件中,我实现了securityFilterChain(),如下所示:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .cors(cors->cors.disable())
            .authorizeRequests()
            .requestMatchers("/auth/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authenticationProvider(authenticationProvider())
            .addFilterBefore(jwtAthFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

虽然我禁用了CORS,但当我从我的登录页面发出请求时,我仍然有问题,该页面是使用JavaScrpit在React中创建的。我使用这个对象axios来发出请求:

axiosInstance.post("/login", credentials)
      .then( 
          res => {
              const val = res.data;
              console.log("Success");
              console.log(val);
              if (val.id !== 0 ) {
                  alert("Logged in!");
                  <Route exact path="/login" element={<User/>}/>
              }
              else
              {
                  alert("Eroare!");
              }
          }
      )
      .catch(error => {
          console.log(error)
      })

当我请求登录时,我得到标题中提到的错误。我试着把不记名密钥放进axios的头中。在postman中,使用承载密钥,我可以毫无问题地与API进行通信。但是在我的React登录页面上,我无法发出任何请求,即使我尝试发送承载密钥。我尝试更改@CrossOrigin注解,指定Access-Control-Allow-Origin,但没有效果。这是我的axios类:

import axios from "axios"
const axiosInstance = axios.create({
    baseURL: "http://localhost:8080/",
    headers: {
        post: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers":
                "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
        }
    }
});

export default axiosInstance;
kuhbmx9i

kuhbmx9i1#

因为你正在做跨域请求。CORS将不允许,直到您配置它。禁用它并不能解决问题。
您可以使用以下配置进行全局配置。

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000") // your reactjs URL
                .allowedMethods("GET", "POST", "PATCH", "PUT", "DELETE")
                .allowedHeaders("Content-Type") // Adjust headers you need to allow
                .allowCredentials(true); // Add only if you want to access cookie
    }

}

还可以在浏览器开发人员控制台中进行检查。请求响应标头。是否包含Access-Control-*头文件?在安全配置中首先使用http.cors()

相关问题