【问题标题】:Reat can't send POST request to Spring Boot appReact 无法向 Spring Boot 应用程序发送 POST 请求
【发布时间】:2020-06-02 23:45:55
【问题描述】:

我有以下问题:我创建了共享一些端点的 Spring Boot API。我也有过滤器,它确定可以使用/不使用 JSON Web Token 到达哪些端点。一切正常,Postman 返回正确的对象,但 React 无法处理。我不知道什么会导致问题。

WebSecurityConfig:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

登录接口:

@CrossOrigin(origins = "http://localhost:3000", allowedHeaders = "*")
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);

    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
    List<String> roles = userDetails.getAuthorities().stream()
            .map(item -> item.getAuthority())
            .collect(Collectors.toList());

    return ResponseEntity.ok(new JwtResponse(jwt,
            userDetails.getId(),
            userDetails.getUsername(),
            roles));
}

React 代码片段:

const authenticate = async () => {
let usr = {
  username: userName,
  password: password
};
await fetch(`http://localhost:8080/auth/login`, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(usr)
}).then((response) => {
  console.log(response);
});

}

请求来自服务器,因为在调试期间我可以读取服务器端的所有数据。我还发现在处理整个请求之前,React 会取消请求。我尝试使用不同的 API(例如https://www.balldontlie.io/#get-all-games)并获取返回代码 200。

Cancelled request

编辑

我可以从另一个 API 端点获取数据,但我必须自己在 fetch/axios 请求中添加 JWToken:

const getInitBooks = async () => {
await axios("http://localhost:8080/api/books/all", {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization' : "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTU5MTE4MDkwMiwiZXhwIjoxNTkxMTgxODAyfQ.aN8mch_CCgeByLGDUkstiNLxV7x3364OEUeDgqyfWVQ"
  },
}).then((response) => {
  console.log(response);
  setBooks(response.data)
  setInitBooks(response.data)
});

所以错误只出现在 POST 请求中。我不知道现在出了什么问题。

解决方案

我想通了,这不是 Spring 问题,而是在 React 函数中添加 e.preventDefault() 有效。

代码sn-p:

const authenticate = async (e) => {
e.preventDefault();
await axios({
  url: "http://localhost:8080/authentication/login/",
  method: "POST",
  data: {
    username: userName,
    password: password
  },
}).then(res => {
  console.log(res);
  setLoggedIn(true);
})
  .catch((err) => console.log(err));
};

【问题讨论】:

    标签: reactjs spring-boot api http-post


    【解决方案1】:

    当我添加我的请求路径时 (localhost:8686/app/addStudent) antMatchers 方法中的 POST 方法,成功运行:

    http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/","/app/**").permitAll()
         .anyRequest()
         .authenticated()
         .and()
         .httpBasic();
    

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2020-05-09
      • 2019-12-18
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2019-10-07
      • 1970-01-01
      相关资源
      最近更新 更多