Node.js 中的 URL 组件编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19077203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL component encoding in Node.js
提问by Kliver Max
I want to send http request using node.js. I do:
我想使用 node.js 发送 http 请求。我愿意:
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 pathlike this:
当我path这样:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6
Its work. But when messageparameter contains any spaces for example tester responseall broke. And in console i see that http use this url:
这是工作。但是当message参数包含任何空格时,例如tester response全部损坏。在控制台中,我看到 http 使用这个 url:
/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester
How to send spaces. Or i just can't use spaces in url?
如何发送空格。或者我不能在 url 中使用空格?
回答by thefourtheye
What you are looking for is called URL component encoding.
您要查找的内容称为URL 组件编码。
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. encodeURIand encodeURIComponent. You need to use encodeURIwhen you have to encode the entire URL and encodeURIComponentwhen the query string parameters have to be encoded, like in this case. Please read this answerfor extensive explanation.
有两个功能可用。encodeURI和encodeURIComponent。encodeURI当您必须编码整个 URL 以及encodeURIComponent必须编码查询字符串参数时,您需要使用,就像在这种情况下一样。请阅读此答案以获得广泛的解释。
回答by David Welborn
The question is for Node.js. encodeURIcomponentis not defined in Node.js. Use the querystring.escape()method instead.
问题是针对 Node.js 的。encodeURIcomponent在 Node.js 中没有定义。请改用该querystring.escape()方法。
var qs = require('querystring');
qs.escape(stringToBeEscaped);
回答by Julien CROUZET
The best way is to use the native module QueryString:
最好的方法是使用本机模块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 installanything.
这是一个本机模块,因此您无需npm install任何操作。

