Node.js中的URL组件编码 [英] URL component encoding in Node.js
问题描述
我想使用node.js发送http请求。我这样做:
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);
});
当我的路径
像这样:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6
它的工作。但是当消息
参数包含任何空格时,例如测试人员响应
都已损坏。在控制台中,我看到http使用此URL:
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
如何发送空格。或者我只是不能在URL中使用空格?
How to send spaces. Or i just can't use spaces in url?
推荐答案
您要找的是网址组件编码。
path: '/api/mainsms/message/send?project=' + project +
'&sender=' + sender +
'&message=' + message +
'&recipients=' + from +
'&sign=' + sign
必须更改为
path: '/api/mainsms/message/send?project=' + encodeURIComponent(project) +
'&sender=' + encodeURIComponent(sender) +
'&message=' + encodeURIComponent(message) +
'&recipients='+encodeURIComponent(from) +
'&sign=' + encodeURIComponent(sign)
注意:
有两种功能可用。 encodeURI
和 encodeURIComponent
。当必须编码整个URL时,需要使用 encodeURI
,当必须编码查询字符串参数时,需要使用 encodeURIComponent
,就像在这种情况下。请阅读此答案以获得详尽的解释。
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.
这篇关于Node.js中的URL组件编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!