Next.js Discord

Discord Forum

Getting data from postgresql functions through pg pool to FE

Unanswered
Common carp posted this in #help-forum
Open in Discord
Common carpOP
Im using Nextjs14 with typescript. Using app router. Doing this in src/app/api/router.ts : import { Pool } from 'pg';

const pool = new Pool({
host: '111.111.111',
port: 1111,
database: 'db',
user: 'user',
password: 'password',
});

export default async function GET(response: Response) {
const client = await pool.connect();
const result = await client.query('SELECT get_x();');
client.release();
response = result.rows[0];
console.log(response);
return response;
}

Then when I'm trying to get the info from that api, whether I do it with my fetching hook: const { fetchApi } = useFetch();

const { showError } = useErrorState();

useEffect(() => {
fetchApi<BusinessPartner[]>('/api/route', {
method: 'GET',
})
.then((response) => {
if ('data' in response && Array.isArray(response.data)) {
setBusinessPartners(response.data);
}
})
.catch((error) => {
console.error('Failed to fetch Business Partner: ', error);
showError('Failed to fetch Business Partner.');
});
}, [businessPartners, showError, fetchApi]);

or just with fetch like:
useEffect(() => {
fetch('/api/route)
.then((response) => response.json())
.then((data) => setBusinessPartners(data))
.catch((error) =>
console.error('Error fetching business partner data: ', error)
);
}, [businessPartners]);

I will always only get the app-index.js:31 Unexpected token '<', "<!DOCTYPE "... is not valid JSON 500 because for some reason what will be the response will not be the data from the calling of the sql function but my entire website again beginning from the layout.tsx. These are the headers the route sends: Request URL:
http://localhost:3000/api/route
Request Method:
GET
Status Code:
200 OK

1 Reply

Common carpOP
Providing more info about the issue, did not put it in the initial post because I ran out of characters: When Im just connected to the db and run SELECT get_x(); from the terminal I get [{"id":7,"name":"general","note":"obiwan","active":true}, {"id":8,"name":"hellothere","note":"kenobi","active":true}] , also as a proof of concept of the pg library working I coded this script: const { Pool } = require('pg');

const pool = new Pool({
// the same pool info as above
});

async function queryDB() {
try {
const client = await pool.connect();
const res = await client.query('SELECT get_x();');
console.log(res.rows[0]);
client.release();
} catch (err) {
console.error(err);
}
}

queryDB(); that when I run with 'node script.js' I get '{
get_x: [
{ id : 7, name: ' general' , note: 'obiwan' , active: true }, { id : 8, name: 'hellothere', note: 'kenobi', active: true }
]
}' in the terminal. So I am pretty sure the problem is on the routing side, but can't figure out where.