我有一个在控制台显示用户及其元数据的请求。我怎样才能让它出现在网站上的表格中(in return()) 这是我的代码:
const apiKey = process.env.CLERK_SECRET_KEY; // Получение значения apiKey из переменной окружения
if (!apiKey) {
console.error('API_KEY не найден в переменных окружения');
process.exit(1);
}
// Формируем заголовки запроса
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
};
// Отправляем GET-запрос для получения списка пользователей
axios.get('https://api.clerk.dev/v1/users', { headers })
.then(response => {
if (response.status === 200) {
const users: Array<any> = response.data;
// Перебираем пользователей и выводим first_name, last_name и метаданные
users.forEach((user: any) => {
const { first_name, last_name, public_metadata } = user;
console.log(`First Name: ${first_name}, Last Name: ${last_name}`);
// Проверяем, является ли public_metadata пустым
if (public_metadata && Object.keys(public_metadata).length === 0) {
// Присваиваем значение public_metadata
user.public_metadata = { "role": 'user' };
// Отправляем PATCH-запрос для обновления метаданных пользователя
const userId = user.id;
axios.patch(`https://api.clerk.dev/v1/users/${userId}/metadata`, {
public_metadata: user.public_metadata
}, { headers })
.then(response => {
if (response.status === 200) {
console.log('Метаданные успешно обновлены');
} else {
console.log('Ошибка при обновлении метаданных');
}
})
.catch(error => {
console.log('Ошибка при выполнении запроса:', error.message);
});
}
console.log('Metadata:', user.public_metadata.role);
});
} else {
console.log('Ошибка при выполнении запроса');
}
})
.catch(error => {
console.log('Ошибка при выполнении запроса:', error.message);
});
export default async function AdminDashboard(params: {
searchParams: { search?: string };
}) {
if (!checkRole("admin")) {
redirect("/");
}
return (
<>
<h1></h1>
<p>This page is restricted to users with the 'admin' role.</p>
</>
);
}
列:名称、user.role(public_metadata)和单独的列为空
我想在网站页面上看到包含所有用户的表格
请帮助我
您没有正确使用 axios 请求,下面是如何实现它。
const apiKey = process.env.CLERK_SECRET_KEY;
const getUsersData = async () => {
if (!apiKey) return;
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
};
const response = await axios.get('https://api.clerk.dev/v1/users', { headers })
const users: Array<any> = response.data;
users.forEach((user: any) => {
const { first_name, last_name, public_metadata } = user;
console.log(`First Name: ${first_name}, Last Name: ${last_name}`);
if (public_metadata && Object.keys(public_metadata).length === 0) {
user.public_metadata = { "role": 'user' };
const userId = user.id;
axios.patch(`https://api.clerk.dev/v1/users/${userId}/metadata`, {
public_metadata: user.public_metadata
}, { headers })
}
});
return users;
}
export default async function AdminDashboard(params: {
searchParams: { search?: string };
}) {
if (!checkRole("admin")) {
redirect("/");
}
const usersData = await getUsersData()
if (!usersData)
return <div>No users</div>
return (
<>
<h1></h1>
<p>This page is restricted to users with the 'admin' role.</p>
<UsersTable users={usersData} />
</>
);
}
// Implementation of table component, you can use some libraries also but this gives you more flexibility in styling, choose whatever you want
export default function UsersTable({users}: {users: any[]}) {
return <table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
{users.map((user) => {
return <tr>
<td>{user.name}</td>
<td>{user.role}</td>
</tr>
})
</table>
}