1
+ import { Form , Input , Button , message } from 'antd' ;
2
+ import axios from 'axios' ;
3
+ import React from 'react' ;
4
+ import { Redirect } from 'react-router' ;
5
+
6
+ axios . defaults . withCredentials = true ;
7
+
8
+ const layout = {
9
+ labelCol : { span : 8 } ,
10
+ wrapperCol : { span : 8 } ,
11
+ } ;
12
+ const tailLayout = {
13
+ wrapperCol : { offset : 5 , span : 8 } ,
14
+ } ;
15
+
16
+ class LoginPage extends React . Component {
17
+ state = {
18
+ redirect : null ,
19
+ loading : false
20
+ }
21
+
22
+ onFinish = ( values : any ) : void => {
23
+ const { username, password } = values ;
24
+
25
+ this . setState ( { loading : true } ) ;
26
+
27
+ axios . post ( "http://localhost:5000/api/login" , {
28
+ username,
29
+ password
30
+ } ) . then ( response => {
31
+ const { username, message : msg } = response . data ;
32
+ window . localStorage . setItem ( "username" , username ) ;
33
+ message . success ( msg ) ;
34
+ this . setState ( { redirect : < Redirect to = "/" /> , loading : false } ) ;
35
+ } ) . catch ( err => {
36
+ this . setState ( { loading : false } ) ;
37
+ if ( err . response ) {
38
+ message . error ( err . response . data . message ) ;
39
+ }
40
+ else {
41
+ message . error ( "Login Failed" ) ;
42
+ }
43
+ } )
44
+ }
45
+
46
+ onFinishFailed = ( err : any ) : void => {
47
+ message . error ( "Failed: " , err ) ;
48
+ }
49
+
50
+ render ( ) {
51
+ const { redirect, loading } = this . state ;
52
+
53
+ if ( window . localStorage . username ) {
54
+ this . setState ( { redirect : < Redirect to = "/" /> } ) ;
55
+ }
56
+
57
+ return (
58
+ < Form
59
+ { ...layout }
60
+ name = "Login"
61
+ onFinish = { this . onFinish }
62
+ onFinishFailed = { this . onFinishFailed }
63
+ >
64
+ { redirect }
65
+ < Form . Item
66
+ label = "Username"
67
+ name = "username"
68
+ rules = { [ { required : true , message : "Please input username!" } ] }
69
+ >
70
+ < Input />
71
+ </ Form . Item >
72
+ < Form . Item
73
+ label = "Password"
74
+ name = "password"
75
+ rules = { [ { required : true , message : "Please input password!" } ] }
76
+ >
77
+ < Input . Password />
78
+ </ Form . Item >
79
+ < Form . Item { ...tailLayout } >
80
+ < Button type = "primary" htmlType = "submit" loading = { loading } > Login</ Button >
81
+ </ Form . Item >
82
+ </ Form >
83
+ )
84
+ }
85
+ }
86
+
87
+ export default LoginPage ;
0 commit comments