我想对这个进行 URL 编码:
SELECT name FROM user WHERE uid = me()
我必须为此下载一个模块吗?我已经有了请求模块。
您可以使用 JavaScript 的 encodeURIComponent
:
encodeURIComponent('select * from table where i()')
给予
'select%20*%20from%20table%20where%20i()'
内置模块 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()'
使用 querystring
的 escape
函数。它生成一个 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'
querystring.stringify()
(在 Nicolas 的回答中)现在似乎返回了一个空字符串。
请注意,URI 编码对查询部分有利,对域不利。域使用 punycode 进行编码。您需要像 URI.js 这样的库来在 URI 和 IRI(国际化资源标识符)之间进行转换。
如果您打算稍后将该字符串用作查询字符串,则这是正确的:
> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'
如果您不想转义 /
、:
和 ?
等 ASCII 字符,请改用 encodeURI
:
> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
但是,对于其他用例,您可能需要 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'
xn--
。它不能作为 url 工作,或者我错过了什么?
http://examplé.org
中的第二个“e”,它不是 ASCII 字符,应显示为 punnycode。
encodeURIComponent(string) 会这样做:
encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"
在查询字符串中传递 SQL 可能不是一个好的计划,
编码URI
encodeURI() 方法用于对完整的 URL 进行编码。此方法对除 ~!$&@#*()=:/,;?+
之外的特殊字符进行编码
编码URI组件
要对 URI 组件中的特殊字符进行编码,您应该使用 encodeURIComponent() 方法。此方法适用于编码 URL 组件,例如查询字符串参数,而不是完整的 URL。
decodeURIComponent
是您解码编码的 URI 的方式。别客气。