I want to send http request using node.js. I do:
http = require(\'http\');
var options = {
host: \'www.mainsms.ru\',
path: \'/api/mainsms/message/se
The best way is to use the native module QueryString :
var qs = require('querystring');
console.log(qs.escape('Hello $ é " \' & ='));
// 'Hello%20%24%20%C3%A9%20%22%20\'%20%26%20%3D'
This is a native module, so you don't have to npm install
anything.
The question is for Node.js. encodeURIcomponent
is not defined in Node.js. Use the querystring.escape()
method instead.
var qs = require('querystring');
qs.escape(stringToBeEscaped);
What you are looking for is called URL component encoding.
path: '/api/mainsms/message/send?project=' + project +
'&sender=' + sender +
'&message=' + message +
'&recipients=' + from +
'&sign=' + sign
has to be changed to
path: '/api/mainsms/message/send?project=' + encodeURIComponent(project) +
'&sender=' + encodeURIComponent(sender) +
'&message=' + encodeURIComponent(message) +
'&recipients='+encodeURIComponent(from) +
'&sign=' + encodeURIComponent(sign)
Note:
There are two functions available. encodeURI and encodeURIComponent. You need to use encodeURI
when you have to encode the entire URL and encodeURIComponent
when the query string parameters have to be encoded, like in this case. Please read this answer for extensive explanation.