首先要说的是,在本地运行时,前端和后端均可正常工作。
我托管了一个Spring Boot后端,该后端使用Spring Security和应该获得POST请求并在Mongo数据库中插入新用户的“ / users” URL在大多数情况下都没有得到该请求。我大部分时间说的是因为请求有时会变得很困难。 对所有网址的所有其他请求都可以正常工作,除了该网址。
使用Postman将POST请求发送到该URL可以正常工作。 另外,我尝试过从本地运行的前端发送请求,但仍然没有成功。
我的后端托管在这里:https://secret-ridge-01197.herokuapp.com/
这是我处理发件人请求的控制器:
@PostMapping("/users")
public User saveUser(@RequestBody User newUser){
String encryptedPassword = encodePasswordToBcrypt(newUser.getPassword());
newUser.setPassword(encryptedPassword);
return userRepository.save(newUser);
}
这些是安全性和核心配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().and().authorizeRequests()
.antMatchers(HttpMethod.POST, "/login","/users").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new LoginFilter("/login",
authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
http.requiresChannel().requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
.requiresSecure();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
config.applyPermitDefaultValues();
source.registerCorsConfiguration("/**", config);
return source;
}
这是来自React的axios调用,其中url为https://secret-ridge-01197.herokuapp.com:
export const addUser = user => async dispatch => {
const res = await axios.post(`${url}/users`, user);
dispatch({
type: ADD_USER,
payload: res.data
});
};
我应该能够通过发送该POST请求将用户插入数据库,但是我注意到在heroku应用程序日志中它是作为OPTION请求接收的。 当我通过Postman将其插入并尝试通过网站登录时,它也可以工作。
This is what I get in the Network panel when I send the request
Heroku上托管的前端:https://dailycalories.herokuapp.com
请注意,前端和后端都分别托管在Heroku上。
谢谢。