基础用法示例
通过实际代码示例快速上手 Optimus CMS,学习常用功能的实现方法。
用户注册与登录
注册新用户
// 使用 fetch API
const response = await fetch('http://localhost:3000/api/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'john_doe',
email: 'john@example.com',
password: 'SecurePass123!',
confirmPassword: 'SecurePass123!'
})
});
const data = await response.json();
console.log('注册成功:', data);用户登录
const response = await fetch('http://localhost:3000/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'john@example.com',
password: 'SecurePass123!'
})
});
const { accessToken, refreshToken } = await response.json();
// 存储 token
localStorage.setItem('accessToken', accessToken);
localStorage.setItem('refreshToken', refreshToken);获取用户信息
// 获取当前用户信息
const token = localStorage.getItem('accessToken');
const response = await fetch('http://localhost:3000/api/users/me', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = await response.json();
console.log('当前用户:', user);提示: 所有需要认证的请求都需要在 headers 中添加 Authorization 字段。
数据查询
获取列表数据(分页)
const response = await fetch(
'http://localhost:3000/api/articles?page=1&limit=10&sort=-createdAt',
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);
const { data, total, page, limit } = await response.json();
console.log(`共 ${total} 条记录,当前第 ${page} 页`);搜索和过滤
const response = await fetch(
'http://localhost:3000/api/articles?keyword=技术&status=published&category=tech',
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);
const articles = await response.json();创建和更新数据
创建文章
const response = await fetch('http://localhost:3000/api/articles', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
title: '我的第一篇文章',
content: '这是文章内容...',
category: 'tech',
tags: ['JavaScript', 'Node.js'],
status: 'draft'
})
});
const article = await response.json();
console.log('文章创建成功:', article);更新文章
const articleId = '123';
const response = await fetch(`http://localhost:3000/api/articles/${articleId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
status: 'published',
publishedAt: new Date().toISOString()
})
});
const updatedArticle = await response.json();文件上传
上传图片
// HTML
<input type="file" id="imageInput" accept="image/*" />
// JavaScript
const input = document.getElementById('imageInput');
const file = input.files[0];
const formData = new FormData();
formData.append('file', file);
const response = await fetch('http://localhost:3000/api/upload/image', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
},
body: formData
});
const { url } = await response.json();
console.log('图片 URL:', url);注意: 上传文件时不要设置 Content-Type header,浏览器会自动设置为 multipart/form-data。
错误处理
try {
const response = await fetch('http://localhost:3000/api/users/me', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || '请求失败');
}
const data = await response.json();
return data;
} catch (error) {
console.error('API 错误:', error.message);
// 处理特定错误
if (error.message.includes('token')) {
// Token 过期,重新登录
window.location.href = '/login';
}
}React Hook 示例
自定义 useFetch Hook
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const token = localStorage.getItem('accessToken');
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) throw new Error('请求失败');
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
// 使用示例
function UserProfile() {
const { data: user, loading, error } = useFetch('/api/users/me');
if (loading) return <div>加载中...</div>;
if (error) return <div>错误: {error}</div>;
return <div>欢迎, {user.username}!</div>;
}