reactjs - 将 axios 请求响应到 Spring Boot REST 服务器身份验证问题
问题描述
我正在尝试向服务器发送一个 axios 发布请求,其中包含表单中提供的用户名和密码作为参数。当我发送请求时,它似乎被发送了两次,一次使用用户名 =“”,另一次使用我提供的用户名。由于第一次发送请求,响应是登录错误。
我尝试使用不起作用的 axios.post 发送请求(在服务器上收到的用户名是空的。我也使用邮递员做了一个发布请求并且它有效(用户名是我在表单正文中提供的用户名,身份验证是成功的)。
这是我在反应中的登录表单
import React, {Component} from 'react'
import axios from 'axios'
import './LoginForm.css'
class LoginForm extends Component{
constructor(props){
super(props);
this.state = {
username : '',
password : ''
};
this.handleRequest = this.handleRequest.bind(this);
}
handleRequest = async () => {
const response = await axios({
method: 'post',
url: 'http://localhost:9090/login',
auth: {
username: this.state.username,
password: this.state.password
}
});
console.log(response);
};
render() {
return (
<div className="login-page">
<div className="form">
<form className="login-form">
<input type="text" name={'username'} value={this.state.username} onChange={(e) => {this.setState({username: e.target.value})}} placeholder="username"/>
<input type="password" name={'password'} value={this.state.password} onChange={(e) => {this.setState({password: e.target.value})}} placeholder="password"/>
<button type={'button'} onClick={this.handleRequest}>login</button>
</form>
</div>
</div>
);
}
}
export default LoginForm;
服务中的 loadByUsername 类
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByUserName(username);
if (user.isPresent()) {
return new MyUserPrincipal(user.get());
} else {
throw new UsernameNotFoundException("Unknown user");
}
}
我填写表单字段,当我按下登录时,我在上面的 loadByUsername 方法中设置了一个断点,第一次参数用户名是“”,在我按 F9 继续之后,该方法再次被调用,它再次在断点处停止但现在用户名是我填写表格的用户名。但是响应是登录错误消息,好像用户名和密码不正确
解决方案
我认为 axios 请求应该如下所示:
const response = await axios({
method: 'post',
url: 'http://localhost:9090/login',
data: {
username: this.state.username,
password: this.state.password
}
});
或者
const response = await axios.post('http://localhost:9090/login',{
username: this.state.username,
password: this.state.password
});
推荐阅读
- google-analytics - 匹配 Google Analytics(分析)添加到 GA 和 BigQuery 之间的购物篮
- firebase - 无法将 XCTest 包上传到 Google Cloud Storage for Firebase 测试实验室
- r - 如何在 Windows 10 上的 R 中安装 X11
- c# - 如何使用.net core 实现图像缓存?
- postgresql - PostgreSQL 查询需要很长时间
- python - 自动生成重载运算符?
- c++ - 如何将 addr_in 结构分配给 uint8_t 数组
- r - 如何在 emacs ess 中设置自定义自动字符替换?
- javascript - 将 Tsheets api 连接到 Google 应用脚本时出错
- python-3.x - chrome 应用程序模式下的 Jupyter 笔记本