【问题标题】:React axios request to Spring Boot REST server authentication problem将 axios 请求响应到 Spring Boot REST 服务器身份验证问题
【发布时间】:2019-10-15 09:04:43
【问题描述】:

我正在尝试向服务器发送一个 axios 发布请求,该服务器具有表单中提供的用户名和密码作为参数。当我发送请求时,它似乎被发送了两次,一次使用用户名 =“”,另一次使用我提供的用户名。响应是登录错误,因为第一次发送请求。

我尝试使用不起作用的 axios.post 发送请求(在服务器上收到的用户名是空的。我也使用邮递员做了一个发布请求并且它有效(用户名是我在表单正文中提供的用户名和认证成功)。

这是我在 react 中的登录表单

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;

Service 中的 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 继续之后,该方法再次被调用并再次停止在断点处,但现在用户名是我填写表格的用户名。但是响应是登录错误消息,好像用户名和密码不正确

【问题讨论】:

  • 如果你找到了解决方案,你介意发布它!在我的用户名是“”并且在声明参数并且它们在我的发布请求中匹配之后遇到了同样的问题..

标签: reactjs spring-boot spring-security


【解决方案1】:

我认为 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
 });

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 2019-02-13
    • 2014-12-25
    • 2019-07-30
    • 2016-10-12
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多