I am trying create a pure Node.js HTTP server to connect my AngularJS Front-End to Postgres Database. But I unable to send a valid response to Front-End as the response to the Front-End gets sent before I could response from DB server.
My Back-End server code is as follows.
const http = require('http');
const pg = require('pg');
let menu = [];
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000,
'Content-Type':'application/JSON',
};
http.createServer((req, res) =>{
client.connect();
client.query('select * from menu;')
.then(res => {
for(row of res.rows) {
let obj = {
'name': row.name,
'price': row.price,
};
menu.push(obj);
}
console.log(menu);
client.end().then(()=>{console.log("Database disconnected");});
}).catch(e => console.error(e.stack));
console.log(menu);
res.writeHead(200, headers);
res.write(JSON.stringify(menu));
res.end();
}).listen(3500, ()=>{
console.log("BackEnd Server online");
});
The console logs from by Back-End is as follows. Kindly suggest me a possible fix.
BackEnd Server online
[]
[
{ name: 'Panner Butter Masala', price: 130 },
{ name: 'Dosa', price: 80 },
{ name: 'Roti', price: 40 },
{ name: 'Pulka', price: 30 },
{ name: 'Sambar vada', price: 70 }
]
Database disconnected
As you can see, before I can get a response from my DB, the response to my front-end already gets sent. So, I am unable to get the requested data.
Use async/await to wait for the response and then send to the client
const http = require('http');
const pg = require('pg');
let menu = [];
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000,
'Content-Type':'application/JSON',
};
http.createServer(async (req, res) =>{
client.connect();
try {
const res = await client.query('select * from menu;');
for(row of res.rows) {
let obj = {
'name': row.name,
'price': row.price,
};
menu.push(obj);
}
} catch (e) {
console.error(e.stack);
}
await client.end();
console.log("Database disconnected")
res.writeHead(200, headers);
res.write(JSON.stringify(menu));
res.end();
}).listen(3500, ()=>{
console.log("BackEnd Server online");
});