我试图从react中的post请求中获取数据,但我无法得到任何回报,响应它是好的,并将数据保存在数据库中,之后我需要在react中返回一个令牌,但我不明白为什么它不起作用。
我试了很多,但没有改变。
这里是react中的请求:
save(registerDTO) {
fetch('http://localhost:8080/api/auth/register',{ method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': '*/*', 'Access-Control-Allow-Credentials': true},body: JSON.stringify( registerDTO )})
.then(data => console.log(data))
.catch(error=>console.warn(error))
}
}
在谷歌浏览器的检查一切正常,但我不能看到响应,即使在那里
响应选项中没有任何内容。
这是我在spring启动侧的代码:
@PostMapping("/register")
public ResponseEntity<Map<String,String>> registerHandler(@RequestBody RegisterDTO registerDTO) {
log.info("User: {}",registerDTO);
return ResponseEntity.ok(registerService.saveUser(registerDTO));
}
在邮差一切工作正常,我甚至不能得到错误信息的反应。
我尝试添加很多cors代码:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000","192.168.1.7:3000"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
// @Bean
// public WebMvcConfigurer corsConfigurer() {
// return new WebMvcConfigurer() {
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**").allowedOrigins("http://localhost:3000/**");
// }
// };
// }
// @Bean
// public CorsConfigurationSource corsConfigurationSource() {
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
// return source;
// }
,我在restcontroller中添加了这个注释:
@CrossOrigin(origins = "http://localhost:3000")
你错过了:
.then(res=> res.json())
在你的取回代码。