gpt4 book ai didi

java - 使用axios从react js调用spring boot get方法时,浏览器显示 "request has been blocked by CORS policy"

转载 作者:行者123 更新时间:2023-12-04 09:36:04 26 4
gpt4 key购买 nike

也许这个问题是重复的,但我没有通过阅读任何帖子来解决这个问题。
当使用 postman 通过向 header 添加 token 来执行获取请求时,它会返回正确的响应。但它不适用于 react js。这是我的 axios get 请求

axios
.get("http://localhost:8080/vehicle/vehicle", {
headers: {
authorization: AuthStr,
},
})
.then((response) => response.data)
.then(
(data) => {
console.log(data);
this.setState({ Vehicles: data });
},
(error) => {
alert(error);
//localStorage.clear();
}
);
我还向 Controller 添加了@CrossOrigin,如下所示。
 @RestController
@RequestMapping("/vehicle")
@CrossOrigin(origins = "http://localhost:3000")
public class VehicleController {}
这是我的配置方法
  @Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request

.authorizeRequests().antMatchers("/authenticate","/user/registerUser","/user/regUser").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.

exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);

// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

}

最佳答案

像这样改变你的配置方法

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

httpSecurity.csrf().disable().authorizeRequests().antMatchers("/authenticate","/user/registerUser","/user/regUser").permitAll().requestMatchers(CorsUtils::isPreFlightRequest).permitAll().
// all other requests need to be authenticated
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);

// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter,
UsernamePasswordAuthenticationFilter.class);

}

关于java - 使用axios从react js调用spring boot get方法时,浏览器显示 "request has been blocked by CORS policy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62581217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com