Browse Source

fetch protected data from cors server

amenpunk 4 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 @@
     "@testing-library/react": "^11.2.7",
     "@testing-library/react-hooks": "^7.0.2",
     "@testing-library/user-event": "^12.8.3",
+    "axios": "^0.26.1",
     "bootstrap": "^5.1.3",
     "date-fns": "^2.27.0",
     "formik": "^2.2.9",

+ 1 - 0
src/Auth/AuthProvider.js

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

+ 19 - 1
src/Pages/Home.jsx

@@ -1,5 +1,5 @@
 import { Col, Row } from 'react-bootstrap'
-import React from 'react'
+import React, { useEffect } from 'react'
 
 import { PersonOutline, VerifiedUser, ListAlt  } from '@mui/icons-material/'
 
@@ -7,7 +7,25 @@ import Actividades from '../Components/Home/Actividades'
 import Candidatos from '../Components/Home/Candidatos'
 import { Card } from '../Components/Card';
 
+import useAuth from '../Auth/useAuth';
+import { Service } from '../Utils/HTTP.js';
+
 export function Home() {
+
+    let auth = useAuth();
+    
+
+    useEffect(() => {
+        let token = auth.getToken();
+        let myService = new Service("/persona/view");
+        myService.get(token)
+        .then( ({data}) => {
+            console.log('Home Response :: ', data)
+        }).catch(e => {
+            console.log('Error Response :: ', e)
+        })
+    } ,[])
+
     return (
         <section >
             <div className="content-section">

+ 1 - 0
src/Pages/Login.jsx

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

+ 3 - 3
src/Pages/Register.jsx

@@ -24,11 +24,10 @@ export function Register() {
     React.useEffect(() => {
         if(auth.isLogged()){
             return navigate('/dashboard/home')
-        }    
+        }
     }, [auth,navigate])
 
 
-//new Date(year, monthIndex, day)
     const TODAY = new Date()
 
     const [activeStep, setActiveStep] = React.useState(0);
@@ -72,7 +71,8 @@ export function Register() {
             label: 'Datos Personales',
             description: 
             <PersonalInfo 
-            client={client} setClient={setClient} 
+            client={client} 
+            setClient={setClient} 
             handleBack={handleBack}
             />
         },

+ 60 - 34
src/Utils/HTTP.js

@@ -1,52 +1,78 @@
-import $ from 'jquery'
-
-export const V2 = (url, data) => {
-    $.ajax({ 
-        type:"POST",
-        url:url,
-        data: JSON.stringify(data), 
-        contentType: 'application/json',
-        success: function(res) {
-            console.log('jquery resp',res);
-            console.log("Added");
-        },
-        error: function(xhr, status, err) {
-            console.error(xhr, status, err.toString());
-        }
-    })  
-}
-
-export const V1 =  async (url, body)  => {
-    let response = await fetch(url, {
-        method: 'POST',
-        headers: {
-            'Accept': 'application/json',
-            'Content-Type': 'application/json'
-        },
-        body : JSON.stringify(body)
-    })
-
-    let req =  await response.json(); 
-    console.log('register request',req )
-}
+import axios from 'axios';
 
 export class Service {
 
     constructor(path){
-        this.base_url = 'http://psicoadmin.ditca.org:8081'
+        this.base_url = 'http://204.48.25.93:8081'
         this.url =  this.base_url + path
+        // this.base_url = 'http://psicoadmin.ditca.org:8081'
         // this.api =  'http://204.48.25.93:8081/user?user=patrik&password=12345'
         // this.api =  'http://psicoadmin.ditca.org:8081/user?user=patrik&password=12345'
     }
 
-    async post(body){
-        console.log('body >> ', body)
+    async get(token){
+        return axios.get(this.url, {
+            headers: {
+                'Authorization': `Bearer ${token}`
+            }
+        })
+        .then((res) => {
+            return res;
+        })
+        .catch((error) => {
+            return error;
+        })
+    }
+
+
+    async get_(token){
+
+        console.log('MY TOKEN ::', token)
+        console.log('MY URL ::', this.url)
+
+
         let response = await fetch(this.url, {
+            headers: new Headers({
+                // "Hwjst" : location.hostname,
+                'Authorization': 'Bearer '+ token,
+            })
+        })
+        return await response.json(); 
+
+    }
+
+    async post(body, token){
+
+        if(!token){
+            let response = await fetch(this.url, {
+                method: "POST",
+                body : JSON.stringify(body)
+            })
+            return await response.json(); 
+        }
+
+
+        const MyHeaders ={
+            'Content-Type': 'application/json',
+            'Authorization': 'Bearer '+ token
+        }
+        
+        console.log('MY TOKEN ::', token)
+        console.log('MY URL ::', this.url)
+        console.log('MY HEADER ::', MyHeaders)
+
+        let response = await fetch(this.url, {
+            credentials: 'include',
             method: "POST",
+            mode: 'cors',
+            cache: 'default',
+            headers: MyHeaders,
             body : JSON.stringify(body)
         })
         return await response.json(); 
+
     }
     
+    
 }