NetLogo Web Extension报"Expected a literal value",如何正确POST列表数据?
解决NetLogo Web Extension提交列表数据的"Expected a literal value"错误
问题原因
你遇到的报错是因为在web:make-request的请求头参数(第三个参数)中,尝试传递动态计算的列表值。该参数的键值对要求值为字面量(直接的字符串、数字等),不能是需要运行时计算的表达式(比如(list xcor ycor heading)),因此触发了语法错误。
正确解决方案
优先推荐通过JSON格式发送数据,这是API交互的通用方式,步骤如下:
- 先将Agent的位置、朝向组织成列表;
- 使用
web:json-stringify将列表转换为JSON字符串; - 在POST请求中,通过请求头指定
Content-Type: application/json,并将JSON字符串作为请求体传递。
修改后的代码:
to follow-path let choice web:make-request "http://127.0.0.1:8000/predict_get" "GET" [] [] ifelse choice = 0 [ forward 1 ] choice = 1 [ right 90 ] choice = 2 [ left 90 ] [ stop ] ; 构建Agent数据列表 let agent-data (list xcor ycor heading) ; 转换为JSON字符串 let json-data web:json-stringify agent-data ; 发送POST请求 web:make-request "http://127.0.0.1:8000/netlogo" "POST" [["Content-Type" "application/json"]] json-data end to move-agent ask turtle (count turtles - 1) [follow-path] end
备选方案(表单格式)
如果你的API要求接收x-www-form-urlencoded格式的表单数据,可以将数据拼接为表单字符串传递:
to follow-path let choice web:make-request "http://127.0.0.1:8000/predict_get" "GET" [] [] ifelse choice = 0 [ forward 1 ] choice = 1 [ right 90 ] choice = 2 [ left 90 ] [ stop ] ; 拼接表单数据字符串 let form-data (word "xcor=" xcor "&ycor=" ycor "&heading=" heading) ; 发送POST请求 web:make-request "http://127.0.0.1:8000/netlogo" "POST" [["Content-Type" "application/x-www-form-urlencoded"]] form-data end to move-agent ask turtle (count turtles - 1) [follow-path] end
内容的提问来源于stack exchange,提问作者sf_Tg
相关产品推荐
相关产品推荐

