node-coap模塊中json的示例代碼缺乏了
.setHeader("Accept","application/json")
,添加後便可正常運行node
const coap = require('coap') // or coap , bl = require('bl') //建立服務器 coap.createServer(function(req, res) { if (req.headers['Accept'] != 'application/json') { res.code = '4.06' return res.end() } //獲得請求數據並解析 var data = req.url.split('/') console.log(data[1] + ':' + data[2] + '\n') //設置響應的格式爲json res.setOption('Content-Format', 'application/json') //發送響應 res.end(JSON.stringify({ cmd: "shutdown" })) }).listen(function() { //啓動監聽服務後建立請求 coap .request({ pathname: '/temperature/32',//請求內容 options: { } }) .setHeader("Accept","application/json")//設置請求頭爲json .on('response', function(res) { //打印響應代號 console.log('response code', res.code) if (res.code !== '2.05') return process.exit(1) res.pipe(bl(function(err, data) { //json解碼,輸出響應cmd字段對應的值 var json = JSON.parse(data) console.log(json.cmd) process.exit(0) })) }) .end() })
$ node son ->temperature:32 response code 2.05 shutdown