Browse Source

fetch protected data from cors server

amenpunk 3 years ago
parent
commit
241a9cc599
6 changed files with 85 additions and 38 deletions
  1. 1 0
      package.json
  2. 1 0
      src/Auth/AuthProvider.js
  3. 19 1
      src/Pages/Home.jsx
  4. 1 0
      src/Pages/Login.jsx
  5. 3 3
      src/Pages/Register.jsx
  6. 60 34
      src/Utils/HTTP.js

+ 1 - 0
package.json

@@ -15,6 +15,7 @@
15 15
     "@testing-library/react": "^11.2.7",
16 16
     "@testing-library/react-hooks": "^7.0.2",
17 17
     "@testing-library/user-event": "^12.8.3",
18
+    "axios": "^0.26.1",
18 19
     "bootstrap": "^5.1.3",
19 20
     "date-fns": "^2.27.0",
20 21
     "formik": "^2.2.9",

+ 1 - 0
src/Auth/AuthProvider.js

@@ -22,6 +22,7 @@ export function AuthProvider ({ children }){
22 22
             Cookies.set('token', undefined)
23 23
             setUser(undefined)
24 24
         },
25
+        getToken : () => Cookies.get('token'),
25 26
         isLogged : () => {
26 27
             try{
27 28
                 let CookiesUser = Cookies.get('token')

+ 19 - 1
src/Pages/Home.jsx

@@ -1,5 +1,5 @@
1 1
 import { Col, Row } from 'react-bootstrap'
2
-import React from 'react'
2
+import React, { useEffect } from 'react'
3 3
 
4 4
 import { PersonOutline, VerifiedUser, ListAlt  } from '@mui/icons-material/'
5 5
 
@@ -7,7 +7,25 @@ import Actividades from '../Components/Home/Actividades'
7 7
 import Candidatos from '../Components/Home/Candidatos'
8 8
 import { Card } from '../Components/Card';
9 9
 
10
+import useAuth from '../Auth/useAuth';
11
+import { Service } from '../Utils/HTTP.js';
12
+
10 13
 export function Home() {
14
+
15
+    let auth = useAuth();
16
+    
17
+
18
+    useEffect(() => {
19
+        let token = auth.getToken();
20
+        let myService = new Service("/persona/view");
21
+        myService.get(token)
22
+        .then( ({data}) => {
23
+            console.log('Home Response :: ', data)
24
+        }).catch(e => {
25
+            console.log('Error Response :: ', e)
26
+        })
27
+    } ,[])
28
+
11 29
     return (
12 30
         <section >
13 31
             <div className="content-section">

+ 1 - 0
src/Pages/Login.jsx

@@ -60,6 +60,7 @@ export function Login() {
60 60
             request
61 61
             .post({})
62 62
             .then( response => {
63
+                    console.log("Service Response :: ", response)
63 64
                 let { token, nombre, apelidos } = response;
64 65
                 toast.success(`Bienvenido ${nombre} ${apelidos}!!`)
65 66
                 token = token.replace("Bearer ", "")

+ 3 - 3
src/Pages/Register.jsx

@@ -24,11 +24,10 @@ export function Register() {
24 24
     React.useEffect(() => {
25 25
         if(auth.isLogged()){
26 26
             return navigate('/dashboard/home')
27
-        }    
27
+        }
28 28
     }, [auth,navigate])
29 29
 
30 30
 
31
-//new Date(year, monthIndex, day)
32 31
     const TODAY = new Date()
33 32
 
34 33
     const [activeStep, setActiveStep] = React.useState(0);
@@ -72,7 +71,8 @@ export function Register() {
72 71
             label: 'Datos Personales',
73 72
             description: 
74 73
             <PersonalInfo 
75
-            client={client} setClient={setClient} 
74
+            client={client} 
75
+            setClient={setClient} 
76 76
             handleBack={handleBack}
77 77
             />
78 78
         },

+ 60 - 34
src/Utils/HTTP.js

@@ -1,52 +1,78 @@
1
-import $ from 'jquery'
2
-
3
-export const V2 = (url, data) => {
4
-    $.ajax({ 
5
-        type:"POST",
6
-        url:url,
7
-        data: JSON.stringify(data), 
8
-        contentType: 'application/json',
9
-        success: function(res) {
10
-            console.log('jquery resp',res);
11
-            console.log("Added");
12
-        },
13
-        error: function(xhr, status, err) {
14
-            console.error(xhr, status, err.toString());
15
-        }
16
-    })  
17
-}
18
-
19
-export const V1 =  async (url, body)  => {
20
-    let response = await fetch(url, {
21
-        method: 'POST',
22
-        headers: {
23
-            'Accept': 'application/json',
24
-            'Content-Type': 'application/json'
25
-        },
26
-        body : JSON.stringify(body)
27
-    })
28
-
29
-    let req =  await response.json(); 
30
-    console.log('register request',req )
31
-}
1
+import axios from 'axios';
32 2
 
33 3
 export class Service {
34 4
 
35 5
     constructor(path){
36
-        this.base_url = 'http://psicoadmin.ditca.org:8081'
6
+        this.base_url = 'http://204.48.25.93:8081'
37 7
         this.url =  this.base_url + path
8
+        // this.base_url = 'http://psicoadmin.ditca.org:8081'
38 9
         // this.api =  'http://204.48.25.93:8081/user?user=patrik&password=12345'
39 10
         // this.api =  'http://psicoadmin.ditca.org:8081/user?user=patrik&password=12345'
40 11
     }
41 12
 
42
-    async post(body){
43
-        console.log('body >> ', body)
13
+    async get(token){
14
+        return axios.get(this.url, {
15
+            headers: {
16
+                'Authorization': `Bearer ${token}`
17
+            }
18
+        })
19
+        .then((res) => {
20
+            return res;
21
+        })
22
+        .catch((error) => {
23
+            return error;
24
+        })
25
+    }
26
+
27
+
28
+    async get_(token){
29
+
30
+        console.log('MY TOKEN ::', token)
31
+        console.log('MY URL ::', this.url)
32
+
33
+
44 34
         let response = await fetch(this.url, {
35
+            headers: new Headers({
36
+                // "Hwjst" : location.hostname,
37
+                'Authorization': 'Bearer '+ token,
38
+            })
39
+        })
40
+        return await response.json(); 
41
+
42
+    }
43
+
44
+    async post(body, token){
45
+
46
+        if(!token){
47
+            let response = await fetch(this.url, {
48
+                method: "POST",
49
+                body : JSON.stringify(body)
50
+            })
51
+            return await response.json(); 
52
+        }
53
+
54
+
55
+        const MyHeaders ={
56
+            'Content-Type': 'application/json',
57
+            'Authorization': 'Bearer '+ token
58
+        }
59
+        
60
+        console.log('MY TOKEN ::', token)
61
+        console.log('MY URL ::', this.url)
62
+        console.log('MY HEADER ::', MyHeaders)
63
+
64
+        let response = await fetch(this.url, {
65
+            credentials: 'include',
45 66
             method: "POST",
67
+            mode: 'cors',
68
+            cache: 'default',
69
+            headers: MyHeaders,
46 70
             body : JSON.stringify(body)
47 71
         })
48 72
         return await response.json(); 
73
+
49 74
     }
50 75
     
76
+    
51 77
 }
52 78