Is it possible to connect postgreSQL directly to Javascript?

without using php, python or odbc?

+8
javascript postgresql
source share
7 answers

You can get the JS driver for Postgres from https://github.com/creationix/postgres-js

This one is for use with node.js. Do not expect to be able to find something that you can run on the client side in a web browser.

+11
source share

No, keep in mind that Javascript only works on the client side when used in a browser, while the database can only be connected from the server. Thus, you will need to call the serveride script in PHP, Python or another server language to get the results.

+3
source share

Yes, perhaps if your javascript is running on node.js. Here is the connector .

+3
source share

I used Postgrest (postgrest.com).

"PostgREST is a standalone web server that turns your PostgreSQL database directly into a RESTful API."

You can then make a request with a URL that returns data in json format.

+3
source share

I have never worked with PostgreSQL, but as far as I know, valid credentials (username and password) are required to access them for databases. With JavaScript, you have no way to hide the username and password, as the script is sent to the client. Theoretically, if you could do this, any client could run queries and do whatever it wanted with your database.

In any case, you cannot access the database from the client side.

+2
source share

It is possible. See the following code. Before using it, you must upgrade Node.js to 7.6.0 or higher. You can use Postgresql by calling only the main(yourQuery) function. Found it on Google.

 const pg = require('pg') // create a config to configure both pooling behavior // and client options // note: all config is optional and the environment variables // will be read if the config is not present var config = { user: 'username', // env var: PGUSER database: 'databaseName', // env var: PGDATABASE password: 'Password', // env var: PGPASSWORD host: 'localhost', // Server hosting the postgres database port: 35432, // env var: PGPORT max: 10, // max number of clients in the pool idleTimeoutMillis: 30000 // how long a client is allowed to remain idle before being closed } const pool = new pg.Pool(config) async function query (q) { const client = await pool.connect() let res try { await client.query('BEGIN') try { res = await client.query(q) await client.query('COMMIT') } catch (err) { await client.query('ROLLBACK') throw err } } finally { client.release() } return res } async function main (queryStr) { try { const { rows } = await query(queryStr); console.log(JSON.stringify(rows)); } catch (err) { console.log('Database ' + err) } } main('SELECT * FROM user where user = \'123\'') 
0
source share

Nope. Javascript is client-side only. You need some kind of server language / interface.

-4
source share

All Articles