Post请求时JSON格式无效?Postgres+Knex环境问题排查
问题
我在Postgres中创建了physical_sites表,其中history列类型为json。API请求函数如下:
const response = await fetch(BASE_URL + "physical_sites", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ data: jobSite }), });
传入的jobSite数据:
{ "physical_site_name": "Here", "physical_site_loc": "test", "created_by": "ME", "status": "Active", "history": [{ "action_date": "2022-07-21T01:22:44.056Z", "action_taken": "Create Job Site", "action_by": "me", "action_by_id": 24, "action_comment": "Initial Upload", "action_key": "1jt9JPRLy7RHJUwmz3kqoy98u" }] }
已通过在线JSON验证工具确认格式正确,后续会向history数组添加更多元素。控制器的create函数:
async function create(req, res) { const result = req.body.data; console.log(result); const data = await knex("physical_sites") .insert(result) .returning("*") .then((results) => results[0]); //insert body data into assets res.status(201).json({ data }); }
持续收到错误:
message: 'insert into "physical_sites" ("created_by", "history", "physical_site_loc", "physical_site_name", "status") values ($1, $2, $3, $4, $5) returning * - invalid input syntax for type json'
不清楚问题出在哪,求分析。
可能的原因与解决办法
- Knex自动序列化异常:Knex处理JSON列时,若请求体已被中间件解析为JS对象,直接插入可能无法正确转换为Postgres接受的JSON格式。需手动对
history字段执行JSON.stringify():const data = await knex("physical_sites") .insert({ ...result, history: JSON.stringify(result.history) }) .returning("*") .then(results => results[0]); - Postgres JSON类型匹配问题:检查
console.log(result)的输出,确认history是JS数组还是JSON字符串。如果是数组,必须手动序列化;如果是字符串,检查是否存在未转义的特殊字符或格式错误。 - 改用
jsonb列类型:Postgres的jsonb类型比json兼容性更好,Knex对其处理更稳定。建议将history列类型修改为jsonb,无需额外改动代码即可正常插入。 - 验证Knex表结构定义:确保Knex的表结构中
history列被正确定义为json或jsonb类型,避免因类型不匹配导致插入失败。
内容的提问来源于stack exchange,提问作者Treesap
相关产品推荐
相关产品推荐

