TypeError: net.Socket is not a constructor
The task: Connect the Postgresql 11 database to the project on React to get data from there.
What I did to connect to the database: Created a new React project:
create-react-app PGTestProject
Then I tried to connect to the database. The actions listed in the "Getting started" section are not enough to get started with the package. For example, it does not indicate how to change the connection parameters to the database. Without this, it is impossible to connect to the created database.
The actions listed in the "Connecting" section are also not enough. The error "net.Socket is not a constructor"
App.js:
import React from 'react';
import logo from './logo.svg';
import './App.css';
async function getDatafromDB(){
const { Pool, Client } = require('pg')
const pool = new Pool({
user: 'postgres',
host: 'server_ip',
database: 'mydb',
password: 'password',
port: 5432,
})
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
pool.end()
})
const pool = new Pool({
user: 'postgres',
host: 'server_ip',
database: 'mydb',
password: 'password',
port: 5432,
})
client.connect()
client.query('SELECT NOW()', (err, res) => {
console.log(err, res)
client.end()
})
}
function App() {
getDatafromDB();
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
An error occurs in the browser console: TypeError: net.Socket is not a constructor
You can’t run pg in the browser. It runs in Node.
Why can't it be run in the browser? There must be a way to connect a website table to Postgres SQL databases.
And send credentials over the wire? If you really want to skip the backend have a look at AWS Amplify and GraphQL.
@dflynn20 I can think of three categories of in-browser pg:
- really terrible and insecure ideas
- cases where it’s easy to proxy queries through a Node backend
- niche uses that are not worth inserting abstractions over Node net interfaces into pg to cater to (unless you want to sponsor brianc for their implementation)
If you have an exception, please share the details that would justify support.
Remember that browsers don’t allow plain socket connections anyway.
@charmander what about deploying to cloudflare workers?
Edit found this: https://github.com/cloudflare/db-connect
The real answer to this is that it is not technically possible, as there is no TCP support in browsers, and no plan for it
@micimize Cloudflare workers don’t run in the browser, as far as I know.