84 lines
2.9 KiB
JavaScript
84 lines
2.9 KiB
JavaScript
// Função para obter a URL base da API
|
|
async function getApiUrl() {
|
|
try {
|
|
const response = await fetch('../../../Site_ItGuys/php/config_url.php'); // Solicita a URL base do PHP
|
|
if (!response.ok) {
|
|
throw new Error('Network response was not ok');
|
|
}
|
|
const data = await response.json();
|
|
return data.apiUrl; // Retorna a URL base
|
|
} catch (error) {
|
|
console.error('Error fetching API URL:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Função para obter o token do localStorage
|
|
function getAuthToken() {
|
|
return localStorage.getItem('x-access-token');
|
|
}
|
|
|
|
// Função para carregar e exibir as imagens protegidas
|
|
async function criarBlocos() {
|
|
try {
|
|
const apiUrl = await getApiUrl(); // Obtém a URL da API a partir do PHP
|
|
const token = getAuthToken(); // Obtém o token JWT do localStorage
|
|
|
|
// Faz uma requisição para obter os dados da rota /mounting
|
|
const response = await fetch(`${apiUrl}/mounting`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'x-access-token': token ? token : ''
|
|
}
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Erro na requisição: ' + response.statusText);
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
// Usar a URL da API para acessar as imagens protegidas
|
|
const profileImageUrl = `${apiUrl}${data.usuario.img_perfil}`;
|
|
const companyLogoUrl = `${apiUrl}${data.empresa.logo}`;
|
|
|
|
// Exibe as imagens protegidas usando os URLs retornados pela API
|
|
loadImage(profileImageUrl, 'profileImage'); // Imagem de perfil do usuário
|
|
loadImage(companyLogoUrl, 'companyLogo'); // Logo da empresa
|
|
|
|
} catch (error) {
|
|
console.error('Erro ao criar blocos:', error);
|
|
document.getElementById('result').innerText = 'Erro ao carregar dados: ' + error.message;
|
|
}
|
|
}
|
|
|
|
// Função para carregar uma imagem protegida com token JWT e exibi-la
|
|
async function loadImage(url, imgElementId) {
|
|
try {
|
|
const token = getAuthToken();
|
|
console.log(token)
|
|
const response = await fetch(url, {
|
|
method: 'GET',
|
|
headers: {
|
|
'x-access-token': token // Se o backend usa um cabeçalho customizado
|
|
}
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Erro ao carregar a imagem: ' + response.statusText);
|
|
}
|
|
|
|
const blob = await response.blob(); // Converte a resposta para um blob
|
|
const imageUrl = URL.createObjectURL(blob); // Cria uma URL temporária para a imagem
|
|
|
|
// Define a URL da imagem no elemento <img> correspondente
|
|
document.getElementById(imgElementId).src = imageUrl;
|
|
} catch (error) {
|
|
console.error('Erro ao carregar a imagem:', error);
|
|
}
|
|
}
|
|
|
|
// Inicia o carregamento das imagens quando o script for carregado
|
|
document.addEventListener('DOMContentLoaded', criarBlocos);
|