source: my-react-app/src/components/Login.js@ 24819a8

main
Last change on this file since 24819a8 was 24819a8, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Authorization layer

  • Property mode set to 100644
File size: 1.8 KB
Line 
1import React, { useState } from 'react';
2import axios from 'axios';
3import {useNavigate} from "react-router-dom";
4
5const Login = ({ onLogin }) => {
6 const navigate = useNavigate();
7 const [credentials, setCredentials] = useState({ username: '', password: '' });
8
9 const handleChange = (e) => {
10 const { name, value } = e.target;
11 setCredentials({ ...credentials, [name]: value });
12 };
13
14 const handleSubmit = async (e) => {
15 e.preventDefault();
16 try {
17 const response = await axios.post('http://localhost:8080/api/login', {
18 email: credentials.username,
19 password: credentials.password
20 });
21 const { token } = response.data;
22 // Store token securely (e.g., using HTTP cookies)
23 localStorage.setItem('token', token);
24
25 navigate("/")
26 } catch (error) {
27 // Handle login failure
28 console.error('Login failed:', error);
29 }
30 };
31
32
33 return (
34 <div>
35 <h2>Login</h2>
36 <form onSubmit={handleSubmit}>
37 <div>
38 <label>Username:</label>
39 <input
40 type="text"
41 name="username"
42 value={credentials.username}
43 onChange={handleChange}
44 />
45 </div>
46 <div>
47 <label>Password:</label>
48 <input
49 type="password"
50 name="password"
51 value={credentials.password}
52 onChange={handleChange}
53 />
54 </div>
55 <button type="submit">Login</button>
56 </form>
57 </div>
58 );
59};
60
61export default Login;
Note: See TracBrowser for help on using the repository browser.