You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kong的Lua脚本中为请求体添加user_id字段?

问题

使用Kong作为API网关,通过Lua脚本修改API请求。服务端要求请求头包含Authorization令牌与Content-Type,当前请求体为空,希望通过Lua脚本为raw格式的请求体添加user_id字段,后续Django应用会通过request_body = json.loads(request.body.decode('utf-8'))读取请求体。

尝试了以下Lua脚本:

local form_data, err, mimetype = kong.request.get_body()
form_data["customer_id"] = customer_obj.user_id
form_data = cjson.encode(form_data)
kong.service.request.set_raw_body(form_data)

但返回报错:

{
    "message": "An unexpected error occurred"
}

解决方法

1. 修复空请求体的nil错误

当请求体为空时,kong.request.get_body()会返回nil,直接给nil添加字段会触发错误。必须先判断并初始化空对象:

local form_data, err, mimetype = kong.request.get_body()
-- 请求体为空时初始化空表
if not form_data then
    form_data = {}
end

2. 显式引入cjson库

脚本里没声明引入cjson的话,Kong会找不到这个JSON编码库,要在脚本开头添加:

local cjson = require "cjson"

3. 强制设置Content-Type头

因为最终传递的是JSON格式请求体,必须确保请求头的Content-Type是application/json,否则Django端解析会失败:

kong.service.request.set_header("Content-Type", "application/json")

4. 校验上下文对象有效性

确认customer_obj和customer_obj.user_id在当前Lua上下文里存在且有值,如果customer_obj是nil,访问user_id会直接抛出错误,可以加个简单判断:

if not customer_obj or not customer_obj.user_id then
    kong.log.err("customer_obj或user_id缺失")
    return kong.response.exit(400, {message = "请求上下文异常"})
end

完整修正脚本

local cjson = require "cjson"

-- 校验上下文参数
if not customer_obj or not customer_obj.user_id then
    kong.log.err("Missing customer_obj or user_id")
    return kong.response.exit(400, {message = "请求上下文错误"})
end

-- 获取并初始化请求体
local form_data, err, mimetype = kong.request.get_body()
if not form_data then
    form_data = {}
end

-- 添加字段并编码为JSON
form_data["customer_id"] = customer_obj.user_id
local json_body = cjson.encode(form_data)

-- 设置请求体与Content-Type头
kong.service.request.set_raw_body(json_body)
kong.service.request.set_header("Content-Type", "application/json")

内容的提问来源于stack exchange,提问作者Frid-j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 13:17:12