Clockify添加用户触发Bad Request 400错误,请求技术协助
解决Clockify添加用户时的400 Bad Request错误
核心问题分析
你的代码里手动对req.body执行了JSON.stringify(),但Axios默认会自动将JavaScript对象序列化为JSON,同时自动设置Content-Type: application/json请求头。手动序列化后再传给Axios,相当于把字符串作为请求体发送,导致Clockify API无法正确解析数据,进而返回400错误。
修复步骤
- 移除手动JSON序列化:直接传递
req.body给Axios,无需JSON.stringify()处理 - 简化请求头配置:可以去掉手动设置的
content-type,让Axios自动处理该头信息
修改后的代码:
const addUser = async (req, res) => { const url = `https://api.clockify.me/api/v1/workspaces/${workspaceId}`; try { console.log("DATA", req.body); // 直接打印原始对象即可 const records = await axios.post(`${url}/users/`, req.body, { headers: { "X-Api-Key": key }, }); console.log("Response", records); res.status(200).json(records); } catch (error) { res.status(error.response.status).json({ msg: `请求失败:Clockify接口返回${error.response.status}错误`, }); console.log("Clockify添加用户出错", error.message, error.response?.data); } };
额外排查点
- 确认
workspaceId是有效且当前API密钥有权限访问的工作区ID - 检查
X-Api-Key是否正确,且该密钥拥有工作区的用户添加权限 - 在catch块中打印
error.response.data,Clockify通常会返回具体错误描述(比如邮箱格式无效、缺少必填字段等),能快速定位问题
内容的提问来源于stack exchange,提问作者Vaidehi S
相关产品推荐
相关产品推荐

