mongo-uri-builder
mongo-uri-builder copied to clipboard
Error: Password contains an illegal unescaped character
With a password that contains '$'
the resulting url produces the error Error: Password contains an illegal unescaped character
when I try to use it with MongoClient.connect
.
In the latest connection string specification, username, password, and hostname should be URL-encoded. So probably you just need to wrap your password in a encodeURIComponent(password). (It would be a nice feature for the uri-builder to do this automatically.)
Hey thanks, @flaviojs and @bgSosh, would you like to submit a PR to address this issue?
As an alternative quick fix, if you bump into this issue you can use the lib this way:
var connectionString = mongoUriBuilder({
username: encodeURIComponent('user$$$$'),
password: encodeURIComponent('pass$$$$'),
host: 'host1',
port: 1111,
replicas: [
{host: 'host2', port: 2222},
{host: 'host3', port: 3333}
],
database: 'db',
options: {
w: 0,
readPreference: 'secondary'
}
});
MongoDB can now use a password with special characters. To do this, add an option to the connection
{ useNewUrlParser: true }
:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const uri = 'mongodb://mydbname:pa$s;w@[email protected]:27017/admin';
MongoClient.connect(uri, { useNewUrlParser: true }, (err, db) => {
assert.strictEqual(null, err);
// ...
db.close();
});
With a password that contains
'$'
the resulting url produces the errorError: Password contains an illegal unescaped character
when I try to use it withMongoClient.connect
.
I am seeing the Error: Password contains an illegal unescaped character on the latest version of mongoDb 4.1.2. In the meantime before it gets fixed I have am using a smaller helper function that splits the uri and encodes the password:
leturi = 'mongodb://mydbname:pa$s;w@[email protected]:27017/admin';
let uriParts = uri.split('@')
let loginDetails = uriParts[0].split(':')
loginDetails[2] = encodeURIComponent(loginDetails[2])
uri = `${loginDetails[0]}:${loginDetails[1]}:${loginDetails[2]}@${uriParts[1]}`
This issue can be fixed by substituting the characters that give issues, like "!" or "?" with their percent encoded characters which will work instead. You can find a list with the codes here: https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding. It isn't the fanciest solution but it works well.
This issue can be fixed by substituting the characters that give issues, like "!" or "?" with their percent encoded characters which will work instead. You can find a list with the codes here: https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding. It isn't the fanciest solution but it works well.
this is working