Javascript 我如何在 Node.js 中对某些内容进行 URl 编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6554039/
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
How do I URl encode something in Node.js?
提问by TIMEX
I want to URL encode this:
我想对这个进行 URL 编码:
SELECT name FROM user WHERE uid = me()
Do I have to download a module for this? I already have the request module.
我必须为此下载模块吗?我已经有了请求模块。
回答by Joe
You can use JavaScript's encodeURIComponent
:
您可以使用 JavaScript 的encodeURIComponent
:
encodeURIComponent('select * from table where i()')
回答by nicolaskruchten
The built-in module querystring
is what you're looking for:
内置模块querystring
正是您要找的:
var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'
回答by Kamrul
Use the escape
function of querystring
. It generates a URL safe string.
使用 的escape
功能querystring
。它生成一个 URL 安全字符串。
var escaped_str = require('querystring').escape('Photo on 30-11-12 at 8.09 AM #2.jpg');
console.log(escaped_str);
// prints 'Photo%20on%2030-11-12%20at%208.09%20AM%20%232.jpg'
回答by Flimm
Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.jsto convert between a URI and IRI (Internationalized Resource Identifier).
请注意,URI 编码适用于查询部分,不适用于域。域使用 punycode 进行编码。您需要像URI.js这样的库来在 URI 和 IRI(国际化资源标识符)之间进行转换。
This is correct if you plan on using the string later as a query string:
如果您打算稍后将该字符串用作查询字符串,则这是正确的:
> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'
If you don't want ASCII characters like /
, :
and ?
to be escaped, use encodeURI
instead:
如果你不想ASCII字符喜欢做/
,:
并?
进行转义,使用encodeURI
来代替:
> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
However, for other use-cases, you might need uri-jsinstead:
但是,对于其他用例,您可能需要uri-js:
> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
回答by John Culviner
encodeURIComponent(string) will do it:
encodeURIComponent(string) 会这样做:
encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"
Passing SQL around in a query string might not be a good plan though,
虽然在查询字符串中传递 SQL 可能不是一个好的计划,