springboot中的Javascript提取和@RequestAttribute

时间:2018-10-08 11:15:55

标签: javascript reactjs spring-boot spring-security axios

我在springboot服务器上有一个身份验证API。当我从POSTMAN调用API时,userDetails对象不为null,并且在客户端获得了成功。但是,当我从reactJS执行的userDetails对象为null且服务器返回500消息时,预检响应没有HTTP正常状态。

有人可以帮我解释一下为什么它在POSTMAN中成功而不在javascript中成功吗?

ReactJS中的代码

var data = {
        "password":"password",
        "username":"uname"
 }

fetch("https://ipaddress:port/module/authenticate", {  
    method: "POST",  
    headers: {  
      "Content-Type": "application/json"
    },  
    body: JSON.stringify(data)  
 }).then(response => {  
...  
    })
    .catch((e) => {  
...  
    })

springboot中的代码

@PostMapping(value = "/module/authenticate ")  
@ResponseBody  
public ResponseEntity<String> authenticate(@RequestAttribute UserDetails userDetails) throws Exception {  
...  
}

公共类UserDetails {

// The username for the logging in user.
private String username;
// The password for the user.
private String password;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

发现POST人员未失败的原因
Post man不会在POST API之前进行OPTIONS调用,因此不会失败。但是,fetch调用会先执行OPTIONS检查是否进行cors访问,并且需要由spring安全处理。参考:Why is an OPTIONS request sent and can I disable it?

一种解决方法是将内容类型设置为纯文本/文本

1 个答案:

答案 0 :(得分:0)

不需要解决方法来处理飞行前请求

在Spring Security中正确配置它

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityAdapter extends WebSecurityConfigurerAdapter {

//... other configuration here

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")