After adding JSON support to IoT Coap, it becomes very interesting, at least we can get the results we want. In the previous article, we introduced some common tools--coap command-line toolset. COAP Client code example
Before we start we need to have a client code so that our server can return the correct data and parse
var coap = require (' Coap ');
var requesturi = ' coap://localhost/';
var url = require (' URL '). Parse (RequestUri + ' id/1/');
Console.log ("Request URL:" + url.href);
var req = coap.request (URL);
var bl = require (' bl ');
Req.setheader ("Accept", "Application/json");
Req.on (' response ', function (res) {
res.pipe (BL (function (err, data) {
var json = json.parse (data);
Console.log (JSON);
}
); Req.end ();
The code is a bit too long and a bit more, but the core is this sentence:
Req.setheader ("Accept", "Application/json");
In that case, we only need to judge at the end of our service,
if (req.headers[' Accept '] = = ' Application/json ') {
//do something
};
This will allow you to return the data. (Reprint reservation: COAP and IoT system returns JSON) COAP server-side code
The server side of the code is relatively simple, to determine
if (req.headers[' Accept '] = = ' Application/json ') {
parse_url (req.url, function (result) {
res.end (result);
});
res.code = ' 2.05 ';
}
Whether the request is in JSON format and returns a 205, which is the content, only when the design is to request a URL to return the corresponding data. Such as
coap://localhost/id/1/
The data that should be requested is ID 1, i.e.
[{id:1, Value: ' Is ID 1 ', sensors1:19, sensors2:20}]
and Parse_url just reads the corresponding data from the database.
function Parse_url (URL, callback) {
var db = new Sqlite3. Database (config["db_name"]);
var result = [];
Db.all ("SELECT * from basic;", function (err, rows) {
callback (json.stringify (rows);
})
}
And it's all displayed, and it's a bit of a bad design, but it's almost there now.