I want to send http request using node.js. I do:
http = require('http');
var options = {
host: 'www.mainsms.ru',
path: '/api/mainsms/message/send?project='+project+'&sender='+sender+'&message='+message+'&recipients='+from+'&sign='+sign
};
http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
}).on('error', function(e) {
console.log('ERROR: ' + e.message);
});
When my path like this:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6
Its work. But when message parameter contains any spaces for example tester response all broke. And in console i see that http use this url:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester
How to send spaces. Or i just can't use spaces in url?
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.
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);
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.
TLDR: Use fixedEncodeURI() and fixedEncodeURIComponent()
MDN encodeURI() Documentation...
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
MDN encodeURIComponent() Documentation...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
Why to Not Use encodeURI() and encodeURIComponent()
It is really not recommended to use encodeURI() and encodeURIComponent(), as they are insufficient to properly handle URI or URL encoding directly. Just like at this piece...
'&message=' + encodeURIComponent(message) +
Let's say that the message var is set to this: "Hello, world! (Really hello!)". So what is that evaluated to?
console.log('&message=' + encodeURIComponent("Hello, world! (Really hello!)"));
Output:
&message=Hello%2C%20world!%20(Really%20hello!)
That's not right! Why weren't ( and ) encoded? After all, according to RFC3986, Section 2.2: Reserved Characters...
If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed.
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
Parens are a sub-delim, but they are not being escaped by encodeURI() or encodeURIComponent().
Related
I have a javascript code that generates emails with links in the body.
Some of the links have spaces within the link, so the link gets cut of.
I tried replacing the spaces with the asacii code but it didn't work.
var lineBreak = "%0D%0A";
function GetMailToInfo(attachment, body) {
attachment = attachment ? attachment.replace(" ","%0D%0A") + lineBreak + lineBreak : "";
body += attachment + signature;
window.location.href = "mailto:" + emailTo + "?subject=" + subject() + "&body=" + body;
}
Any idea on how to solve that?
Use encodeURIComponent to properly escape special characters in URLs:
window.location.href =
"mailto:" + encodeURIComponent(emailTo) +
"?subject=" + encodeURIComponent(subject()) +
"&body=" + encodeURIComponent(body);
Your problem is most likely because String.replace only replaces the first occurrence when using a string as the first parameter. See this MDN documentation.
I would suggest either looping:
while (attachment.indexOf(" ") >= 0) {
attachment = attachment.replace(" ", "%0A%0D");
}
Or using RegEx to perform a pattern-based replacement.
However, Quentin's solution is the proper way to go about encoding strings to be safe for URI use. My answer here is for the more general case where it may not be a URI string.
i am using inline editing in my form's text area where it works as it should be , but when the text are string contains & sign it is only saving up to the & sign. so how can i url encode in javascript the & sign so my php scripts gets it and save in mysql as & again.
this is my current code and desc is the string that might contain & sign occasionally
var field_userid = $(this).attr("id") ;
var desc = $(this).val() ;
$.post('includes/update-property-modal.php' , field_userid + "=" + desc, function(data){ });
If you want to do it the way you are currently do it, you need to encode it.
$.post('includes/update-property-modal.php' , field_userid + "=" + encodeURIComponent(desc), function(data){ });
Why not just use an object?
var self = this,
params = {};
params[self.id] = self.value;
$.post('includes/update-property-modal.php',params,function(data){
// whatever thine wish may be
});
This should manage the existence of the '&' internally, and really is the better way to send parameters with $.ajax().
Use encodeURIComponent() to escape all characters except the following: alphabetic, decimal digits, _ - . ~ ! * ' ( )
$.post('includes/update-property-modal.php', field_userid + "=" + encodeURIComponent(desc), function(data) {});
But in the case of jQuery's ajax() and your example, it is better to use it this way:
var params = {
$(this).attr('id'): $(this).val()
};
$.post('includes/update-property-modal.php', params, function(data) {});
I want to encode a string to UTF-8 in JavaScript. In java we use URLEncoder.encode("String", "UTF-8") to achieve this.
I know we can use encodeURI or encodeURIComponent but it is producing different output than URLEncoder.encode
Can anyone please suggest any available JS method that can be used to achieve same output as URLEncoder.encode.
NOTE:
Due to restrictions I cannot use jQuery.
I don't know if this javaURLEncode() function is a spot-on match for Java's URLEncoder.encode method, but it might be close to what you're looking for:
function javaURLEncode(str) {
return encodeURI(str)
.replace(/%20/g, "+")
.replace(/!/g, "%21")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/~/g, "%7E");
}
var testString = "It's ~ (crazy)!";
var jsEscape = escape(testString);
var jsEncodeURI = encodeURI(testString);
var jsEncodeURIComponent = encodeURIComponent(testString);
var javaURLEncoder = javaURLEncode(testString);
alert("Original: " + testString + "\n" +
"JS escape: " + jsEscape + "\n" +
"JS encodeURI: " + jsEncodeURI + "\n" +
"JS encodeURIComponent: " + jsEncodeURIComponent + "\n" +
"Java URLEncoder.encode: " + javaURLEncoder);
found one more character should be replaced
.replace(/\$/g, "%24")
I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a +, thus breaking the search. How can I either replace the space with a +, or just safely URL Encode the string?
$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Better way:
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
use jQuery.param().....
Description: Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.
try this one
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');
alert(window.location.href/&name=" + escape(name_var) + "&id=" + escape(id_var));
thanks
No, it's not correct.
alert(window.location.href + "&name=" + encodeURIComponent(name_var) + "&id=" + encodeURIComponent(id_var));
You have a syntax error in your code, the / that follows window.location.href
Use the concatenation operator, + - myString + "more string"
escape is deprecated, use encodeURI() and encodeURIComponent()