我如何在Node.js中对URl进行编码?

时间:2011-07-01 23:09:55

标签: javascript url node.js

我想对此进行网址编码:

SELECT name FROM user WHERE uid = me() 

我是否必须为此下载模块?我已经有了请求模块。

6 个答案:

答案 0 :(得分:520)

您可以使用JavaScript的encodeURIComponent

encodeURIComponent('select * from table where i()')

答案 1 :(得分:115)

您正在寻找内置模块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()'

答案 2 :(得分:41)

使用escape的{​​{1}}功能。它会生成一个URL安全字符串。

querystring

答案 3 :(得分:14)

请注意,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'

答案 4 :(得分:10)

encodeURIComponent(string)将执行此操作:

encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"

在查询字符串中传递SQL可能不是一个好计划,

see this one

答案 5 :(得分:-3)

解决方案,不编码包含字符“或”的查询。 在查询中传递SQL字符串是一种biq安全风险。

function encodeSQLInjection(query){
  return encodeURIComponent(query).replace(/'/g,"%27").replace(/"/g,"%22");
}
encodeSQLInjection("DELETE FROM users WHERE name LIKE '%noob%'") 
相关问题