Let's say I have a remote Postgres database:
postgres://<user>:<passwd>@foo.us-west-1.compute.amazonaws.com:5432/<dbname>
The usual way to connect to this database would be to spin up a backend server and send requests through this using an SQL library. However, I'd like to know if it's possible to connect to the DB directly from a browser environment using plain JS, e.g. using fetch
.
I tried a few things but none of them seem to work.
-
givesfetch("postgres://<user>:<passwd>@foo.us-west-1.compute.amazonaws.com:5432/<dbname>")
URL scheme "postgres" is not supported
. -
givesfetch("http://foo.compute-1.amazonaws.com:5432/<dbname>")
net::ERR_EMPTY_RESPONSE
. -
returnsfetch("https://foo.compute-1.amazonaws.com:5432/<dbname>")
net::ERR_CONNECTION_CLOSED
.
I guess I need to put the credentials in my request somewhere, but I'm not sure where to put them.
CodePudding user response:
fetch
works on HTTP layer and Postgres natively do not support communication on HTTP. So it is not possible to query your DB directly from the browser.
However, there are tools that you can configure like Postgrest which creates a HTTP interface on the top of your DB layer which you can use to communicate with DB.
If you are using a managed database like AWS RDS then you can use their SDKs to get data from the browser.