How do I URl encode something in Node.js?

How do I URl encode something in Node.js?

I want to URL encode this:
SELECT name FROM user WHERE uid = me()

Do I have to download a module for this? I already have the request module.


Solution 1:

You can use JavaScript’s encodeURIComponent:

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

Solution 2:

The built-in module querystring is what you’re looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'

Solution 3:

Use the escape function of querystring. It generates a URL safe string.

var escaped_str = require('querystring').escape('Photo on 30-11-12 at 8.09 AM #2.jpg');
// prints 'Photo%20on%2030-11-12%20at%208.09%20AM%20%232.jpg'

Solution 4:

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.js to convert between a URI and IRI (Internationalized Resource Identifier).

This is correct if you plan on using the string later as a query string:

> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")

If you don’t want ASCII characters like /, : and ? to be escaped, use encodeURI instead:

> encodeURI("http://examplé.org/rosé?rosé=rosé")

However, for other use-cases, you might need uri-js instead:

> var URI = require("uri-js");
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))

Solution 5:

encodeURIComponent(string) will do it:

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,

Related:  How to escape apostrophe or quotes on a JSP (used by JavaScript)

see this one

Solution 6:

The solutions, do not encode queries containing characters ” or ‘ .
Passing SQL strings in query is a biq security risk.

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