使用 axios 从 react js 调用 Spring Boot get 方法时,浏览器显示“请求已被 CORS 策略阻止”
Posted
技术标签:
【中文标题】使用 axios 从 react js 调用 Spring Boot get 方法时,浏览器显示“请求已被 CORS 策略阻止”【英文标题】:browser says " request has been blocked by CORS policy" when calling to a spring boot get method from react js using axios 【发布时间】:2020-10-16 06:10:15 【问题描述】:也许这个问题是重复的,但我没有通过阅读任何帖子来解决这个问题。
当通过使用邮递员向标头添加令牌来执行获取请求时,它会返回正确的响应。但它不适用于反应 js。这是我的 axios 获取请求
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();
);
我还向控制器添加了@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);
【问题讨论】:
【参考方案1】:像这样改变你的配置方法
@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);
【讨论】:
以上是关于使用 axios 从 react js 调用 Spring Boot get 方法时,浏览器显示“请求已被 CORS 策略阻止”的主要内容,如果未能解决你的问题,请参考以下文章
为啥我的 axios 使用 React.useEffect 一遍又一遍地从 Rails 后端获取调用?
React.js - 如何使用 axios POST 方法将数据从 div 传递到函数?
使用 Axios 将对象从 React.js 发布到 PHP