首页 > 解决方案 > curl 在 content-type: application/json 上发送空 json

问题描述

我使用 curl 和 POST 方法将 json 格式的 cpu 和内存使用情况从 Ubuntu 发送到 Node.js API。但是,Node.js 服务器上的 json 数据是空的。

Ubuntu 上的 Bash 脚本

top -b -n 2 -d 0.5 > top.txt
cpu_i=$(grep Cpu top.txt | cut -d ',' -f 4 | cut -d ' ' -f 2)
cpu=$(echo $cpu_i | cut -d ' ' -f 2)
echo $cpu

mem=$(grep "KiB Mem :" top.txt | cut -d ':' -f 2)
#echo $mem
mem_used=$(echo $mem | cut -d ',' -f 3 | cut -d ' ' -f 2)
echo $mem_used

curl --header "Content-Type: application/json" -d "{\"cpu\":\"$cpu\", \"memory\":\"$mem_used\",\"device\":\"ubuntu\"}" http://192.168.10.10:4000/collector

Node.js 服务器上的输出

{} 远程地址:::ffff:192.168.10.5

标签: bashcurlcontent-type

解决方案


如果我没记错的话,httpverb 默认设置为 get 。如果您打算发布它,请使用-X POST. 这可能会解决您的问题,因为 curl 命令是可以的。

curl -X POST --header "Content-Type: application/json" -d "{\"cpu\":\"$cpu\", \"memory\":\"$mem_used\",\"device\":\"ubuntu\"}" http://192.168.10.10:4000/collector

推荐阅读