let posts = [
{
id: 1,
title: '欢迎来到 DevForge 论坛!',
content: '这是第一个帖子,欢迎大家交流技术心得!',
author: { username: 'admin' },
tags: ['欢迎', '公告'],
createdAt: new Date().toISOString(),
replyCount: 0
},
{
id: 2,
title: 'C++ 还是 Rust?大家来讨论一下',
content: '最近在纠结学 C++ 还是 Rust,有没有大佬给点建议?',
author: { username: 'cpp_fan' },
tags: ['C++', 'Rust', '编程语言'],
createdAt: new Date(Date.now() - 3600000).toISOString(),
replyCount: 3
}
];
let nextId = 3;
module.exports = async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') return res.status(200).end();
if (req.method === 'GET') {
return res.json({ posts });
}
if (req.method === 'POST') {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: '请先登录' });
}
const { title, content, tags } = req.body;
if (!title || !title.trim()) {
return res.status(400).json({ error: '标题不能为空' });
}
if (!content || !content.trim()) {
return res.status(400).json({ error: '内容不能为空' });
}
const newPost = {
id: nextId++,
title: title.trim(),
content: content.trim(),
author: { username: 'admin' },
tags: tags ? tags.split(',').map(t => t.trim()).filter(Boolean) : [],
createdAt: new Date().toISOString(),
replyCount: 0
};
posts.unshift(newPost);
return res.json({ success: true, message: '发布成功', post: newPost });
} catch (error) {
return res.status(400).json({ error: '请求格式错误' });
}
}
return res.status(405).json({ error: 'Method not allowed' });
};
大家帮忙看一下吧