@@ -16,28 +16,46 @@ fistForm.addEventListener("submit", (e) => e.preventDefault());
1616secondForm . addEventListener ( "submit" , ( e ) => handleLogin ( e ) ) ;
1717
1818async function handleLogin ( e ) {
19- e . preventDefault ( ) ;
20-
21- const email = secondForm . querySelector ( "input[type='text']" ) . value ;
22- const password = secondForm . querySelector ( "input[type='password']" ) . value ;
23-
24- try {
25- const response = await fetch ( "https://fakestoreapi.com/auth/login" , {
26- method : "POST" ,
27- headers : {
28- "Content-Type" : "application/json" ,
29- } ,
30- body : JSON . stringify ( { email, password } ) ,
31- } ) ;
32- if ( ! response . ok ) {
33- throw new Error ( "Login failed! Please check your credentials." ) ;
34- }
35- const data = await response . json ( ) ;
36- localStorage . setItem ( "token" , data . token ) ;
37- alert ( "Login successful!" ) ;
38-
39- } catch ( error ) {
40- console . error ( error ) ;
41- alert ( error . message ) ;
42- }
43- }
19+ e . preventDefault ( ) ;
20+
21+ const emailInput = e . target . querySelector ( "input[type='text']" ) ;
22+ const passwordInput = e . target . querySelector ( "input[type='password']" ) ;
23+
24+ if ( ! emailInput || ! passwordInput ) {
25+ console . error ( "Input fields not found" ) ;
26+ return ;
27+ }
28+
29+ const email = emailInput . value ;
30+ const password = passwordInput . value ;
31+
32+ if ( ! email || ! password ) {
33+ alert ( "Please enter both username and password." ) ;
34+ return ;
35+ }
36+
37+ try {
38+ const response = await fetch ( 'https://fakestoreapi.com/auth/login' , {
39+ method : 'POST' ,
40+ headers : {
41+ 'Content-Type' : 'application/json' ,
42+ } ,
43+ body : JSON . stringify ( {
44+ username : email ,
45+ password : password
46+ } ) ,
47+ } ) ;
48+
49+ if ( ! response . ok ) {
50+ throw new Error ( "Login failed! Please check your credentials." ) ;
51+ }
52+
53+ const data = await response . json ( ) ;
54+ localStorage . setItem ( "token" , data . token ) ;
55+ alert ( "Login successful!" ) ;
56+
57+ } catch ( error ) {
58+ console . error ( error ) ;
59+ alert ( error . message ) ;
60+ }
61+ }
0 commit comments