我想把这个URL编码:
SELECT name FROM user WHERE uid = me()
我需要为此下载一个模块吗?我已经有了请求模块。
我想把这个URL编码:
SELECT name FROM user WHERE uid = me()
我需要为此下载一个模块吗?我已经有了请求模块。
当前回答
你可以使用JavaScript的encodeURIComponent:
encodeURIComponent('select * from table where i()')
给
'select%20*%20from%20table%20where%20i()'
其他回答
请注意,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'
你可以使用JavaScript的encodeURIComponent:
encodeURIComponent('select * from table where i()')
给
'select%20*%20from%20table%20where%20i()'
encodeURI
encodeURI()方法用于编码一个完整的URL。该方法编码除~!$&@#*()=:/,;?+
encodeURIComponent
要在URI组件中编码特殊字符,应该使用encodeURIComponent()方法。此方法适用于编码URL组件,例如查询字符串参数,而不是完整的URL。
使用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'
encodeURIComponent(string)会这样做:
encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"
⚠️在查询字符串中传递SQL可能不是一个好计划:请看这个