I have the following code
const coap = require('coap');
const url = require('url');
const server = coap.createServer((req, res) => {
const uri = req.url; // Get the requested URI
const path = uri.split('?')[0]; // Extract path from the URI
if (path === '/variable') {
handleVariable(req, res);
} else if (path === '/update') {
handleUpdate(req, res);
} else if (path === '/observe') {
handleObserve(req, res);
} else if (path === '/test') {
handleTest(req, res);
} else {
// Handle other URIs if needed
console.log(`${uri} not found`);
res.statusCode = 404;
res.end('Not Found');
}
});
// Start the CoAP server on port 5683 (default CoAP port)
server.listen(() => {
console.log('CoAP server started on port 5683');
});
function handleTest(req, res) {
if (req.method == 'GET') {
const parsedUrl = url.parse(req.url, true);
const id = parsedUrl.query.id;
console.log(req);
console.log(req.url);
console.log(id);
// Respond with the current value of the variable
res.write("Test suttessful");
res.end();
}
}
and I am using coap-client
to send requests to the server. The problem I am facing is when I send multiple query parameters.
this is my command
coap-client -m get coap://127.0.0.1:5683/variable?uid=one&did=2
for some reason when I print the URL I receive, it only includes the first query parameter and not the second
I end up receiving only
/variable?uid=one
and nothing after that.
You are running the coap-client
command from a shell, presumably a UNIX shell.
The '&' character is interpreted by the shell to run the previous command in the background, so what your client program is really doing is
coap-client -m get coap://127.0.0.1:5683/variable?uid=one &
did=2
(did=2 is an assignment and thus doesn't cause an error; sending the coap-client program to the background is barely noticeable because it returns fast.
If you protect the URI from the shell's processing by quoting it, you should get the right results:
coap-client -m get "coap://127.0.0.1:5683/variable?uid=one&did=2"
(Related notes: You don't need to specify port 5683 because it is the default port. When you use IPv6 addresses such as coap-client -m get "coap://[::1]/variable"
, the quotes will also prevent shell processing of the brackets.)