I create a full-stack system written on the server side with JAVA and spring and a client side with react.js I made a JWT system in order to connect to the system and also sign up. The system works on the server side and I want to unify it into the appropriate component And for some reason nothing works, it's important to emphasize that I'm brand new with react.js and this is the first project I create with react.js
this is the login.jsx component:
import React, { Component } from 'react'
import AuthService from '../services/AuthService';
import "./Login.css";
class login extends Component{
constructor(props){
super(props);
this.state={
username: '',
password: '',
}
this.signin = this.signin.bind(this);
}
signin(){
let loginRequest = {username: this.state.username, password: this.state.password};
AuthService.signin(loginRequest).then(res=>{
this.props.history.push('/home');
});
console.log('employee => ' + JSON.stringify(loginRequest));
}
changeUserNameHandler= (event) => {
this.setState({username: event.target.value});
}
changePasswordHandler= (event) => {
this.setState({password: event.target.value});
}
render() {
return (
<section className="container">
<div className="row">
<div className="col-md-6">
<div className="card">
<form className="box">
<h1>Login</h1>
<p className="text-muted"> Please enter your User Name and Password!</p>
<input onChange={this.changeUsertNameHandler} autoComplete="off" type="text" name="username" placeholder="Username"/>
<input onChange={this.changePasswordHandler} autoComplete="off" type="password" name="password" placeholder="Password"/>
<a className="forgot text-muted" href="#">Forgot password?</a>
<input onClick={this.signin} type="submit" name="" value="Login" href="#"/>
<div className="col-md-12">
<ul className="social-network social-circle">
<li><a href="#" className="icoFacebook" title="Facebook"><i className="fab fa-facebook-f"></i></a></li>
<li><a href="#" className="icoGoogle" title="Google +"><i className="fab fa-google-plus"></i></a></li>
</ul>
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
</div>
</div>
</form>
</div>
</div>
</div>
</section>
);
}
}
export default login;
and this is the AuthController(java spring):
package com.example.coffeedemo.Controller;
import com.example.coffeedemo.model.ERole;
import com.example.coffeedemo.model.Role;
import com.example.coffeedemo.model.User;
import com.example.coffeedemo.repository.RoleRepository;
import com.example.coffeedemo.repository.UserRepository;
import com.example.coffeedemo.requests.LoginRequest;
import com.example.coffeedemo.requests.SignupRequest;
import com.example.coffeedemo.response.JwtResponse;
import com.example.coffeedemo.response.MessageResponse;
import com.example.coffeedemo.security.JwtUtils;
import com.example.coffeedemo.service.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
System.out.println(userRepository.findByUsername(loginRequest.getUsername()));
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
System.out.println(strRoles);
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
In the current situation, when I try to connect nothing happens.. even printing to console.log..
Would appreciate help Thank you !!
Change your input
to a normal <button onClick={this.signin}>Login</button>
.
edit and if that doesn't help, show us your AuthService.signin
function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.