I am trying to return all the details of the product and display them in table format
I have already tried this in my api
app.get('/test',(req,res) => {
const client = new Client({
connectionString: connectionString
})
client.connect()
client.query('select * from product',(err,res) =>{
console.log(err,res)
if(err){
console.log(err);
}else{
console.log(res);
}
client.end()
})})
How do i return this res in node?
You are hiding the outside res in the route handler with the inside res of the query result.
I have to make some assumptions about your query client, but if the inside res is the array of rows, simply pass it to the res.json() function (another assumption is you are using Express).
My suggestion:
app.get('/test', (req, res) => {
const client = new Client({
connectionString: connectionString
})
client.connect()
client.query('select * from product', (err, rows) => {
console.log(err, rows)
if (err) {
console.log(err);
} else {
console.log(rows);
res.json(rows);
}
client.end()
})
});
Related
I have built and API with Express to POST a new job in a project I am currently working on. The GET requests work fine, also the DEL, but the POST one is not working. I am connected to a POSTGRES database.
I have defined the following path for the API:
app.use('/api/jobs', jobRoutes);
so when I send a POST request like below:
localhost:4000/api/jobs/createjob
it should work. What is also weird, is that the code was working perfectly before, but now I can't seem to figure it out anymore. I tried looking elsewhere, but I couldn't find any solution when getting this kind of error with APIs.
My API looks like the following:
router.post("/createjob", async (req, res) => {
try {
const {job} = req.body;
const newJob = await pool.query("INSERT INTO job(job_title, job_department, country_id, description, expiration_date) VALUES($1, $2, $3, $4, $5) RETURNING *", [job.job_title, job.job_department, job.country_id, job.description, job.expiration_date]);
res.json(newJob.rows);
} catch (error) {
console.error(error.message);
}
})
I am making the POST request with Postman, and the body looks like this:
{
"description": "job_description",
"job_title": "Back End Developer"
}
When I send the requests, in the terminal shows this error:
Cannot read properties of undefined (reading 'job_title')
Full code of the Routes:
const express = require("express");
const router = express.Router();
const pool = require("../db");
// routes
// get all jobs
router.get('/alljobs', async (req, res) => {
try {
const allJobs = await pool.query("SELECT * FROM job");
res.json(allJobs.rows)
} catch (error) {
console.error(error.message);
}
})
// GET a single job
router.get('/job/:id', async (req, res) => {
try {
const {id} = req.params;
const job = await pool.query("SELECT * FROM job WHERE job_id = $1 ", [id]);
res.json(job.rows)
} catch (error) {
console.error(error.message);
}
})
// create a job
router.post("/createjob", async (req, res) => {
try {
const {job} = req.body;
const newJob = await pool.query("INSERT INTO job(job_title, job_department, country_id, description, expiration_date) VALUES($1, $2, $3, $4, $5) RETURNING *", [job.job_title, job.job_department, job.country_id, job.description, job.expiration_date]);
res.json(newJob.rows);
} catch (error) {
console.error(error.message);
}
})
// update a job
router.patch("/updatejob/:id", async (req, res) => {
try {
const {id} = req.params;
const {description} = req.body;
const updateJob = await pool.query("UPDATE job SET description = $1 WHERE job_id = $2", [description, id]);
res.json(updateJob.rows);
} catch (error) {
console.error(error.message);
}
})
// delete a job
router.delete("/deletejob/:id", async (req, res) => {
try {
const {id} = req.params;
const deleteJob = await pool.query("DELETE FROM job WHERE job_id = $1", [id]);
res.json(deleteJob.rows);
} catch (error) {
console.error(error.message);
}
})
// get all countries
router.get("/countries", async (req, res) => {
try {
const allCountries = await pool.query("SELECT * FROM countries");
res.json(allCountries.rows)
} catch (error) {
console.error(error.message);
}
})
// //create new user
// router.post("/newuser", async (req, res) => {
// try {
// const {user} = req.body;
// const newUser = await pool.query("INSERT INTO users(user_name, email, password, is_candidate, is_recruiter) VALUES($1, $2, $3, $4, $5) RETURNING *", [user.user_name, user.email, user.password, user.candidate, user.recruiter]);
// res.json(newUser.rows);
// } catch (error) {
// console.error(error.message);
// }
// })
module.exports = router;
Full code of my server.js file:
const express = require("express");
const router = require("./routes/jobRoutes");
const jobRoutes = require("./routes/jobRoutes");
const cors = require("cors");
//creates express app
const app = express();
app.use(express.json());
app.use(cors());
//middleware
app.use((req,res,next) => {
console.log("req.path", req.method);
next();
})
app.get("/status", (req, res, next) => {
res.send("connected");
});
// for every other request
app.use('/api/jobs', jobRoutes);
// more middleware
app.use((err, req, res, next) => {
let status = err.status || 500;
let message = err.message;
console.error(err);
return res.status(status).json({
error: { message, status },
});
});
//listen for requests
app.listen(4000, () => {
console.log("listening on port 4000")
});
I tried looking elsewhere, but I couldn't find any solution when getting this kind of error with APIs. The GET and the DEL requests work as expected.
app.post('', (req, res) => {
pool.getConnection((err, connection) => {
if (err) throw err
console.log('connected as id' + connection.threadID)
const params = req.body;
connection.query('INSERT INTO beers SET ?', [params], (err, rows) => {
connection.release()
if (!err) {
res.send('Successfully added record of name' + params.name)
} else {
console.log(err)
}
})
console.log(req.body)
})
})
I'm not sure what kind of library you're using to communicate with the DB, but I reckon, it should look more like
connection.query('INSERT INTO beers(someColumn, someOtherColumn) VALUES (?,?)', [params.valueOfSomeColumn, params.valueOfSomeOtherColumn],...blabla the rest)
Looks like you're mixing up the INSERT and UPDATE statements. INSERT doesn't use SET
Usually this sort of basic DB libs connect the ? characters with the value from an array
i'm trying to retrieve all entires from mongo yet I keep on getting an error that I couldn't find any while having there are some entries.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';
tryMongo();
function tryMongo() {
MongoClient.connect(url, (err, client) => {
if (err) return console.log('Cannot connect to DB');
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('toy');
collection.find().toArray((err, docs) => {
if (err) return console.log('cannot find toys');
console.log('found these:');
console.log(docs);
});
client.close();
});
}
this is the error i'm getting :
Server listening on port 3030!
Connected successfully to server
cannot find toys
I have also added a picture of mongo
appreciating any kind of help!
You are closing mongo connection before you get response from server. Move client.close(); inside toArray callback.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';
tryMongo();
function tryMongo() {
MongoClient.connect(url, (err, client) => {
if (err) return console.log(err);
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('toy');
collection.find().toArray((err, docs) => {
if (err) {
console.log(err);
} else {
console.log('found these:');
console.log(docs);
}
client.close();
});
});
}
I am trying to convert my pg pool queries to Knex and am having an issue with this query:
router.post('/register', validInfo, async (req, res, next) => {
const { email, name, password } = req.body;
try {
const user = await pool.query('SELECT * FROM users WHERE user_email = $1', [email]);
res.json(user);
} catch (err) {
console.error(err);
}
});
Here is what I have so far:
router.post('/register', validInfo, async (req, res, next) => {
const { email, name, password } = req.body;
try {
//Check if user exists
const user = await knex('users')
.select('*')
.where('user_email', $1, [email]);
res.json(user);
} catch (err) {
console.error(err);
}
});
When I create a new user in Postman I should receive an empty array but it's not working. What needs to change in order to match the first query?
I am just trying to write simple register/login system.
I am trying to find if username exists. Here is the steps :
Go localhost:3000/users/register page
Fill in all fields and click register button
Checking my command line if username exists it should print it with console.log
Everything works fine until now.
When I go back to the register page, I fill in all fields again and click register button. Then it throws it in command line :
Error: Client has already been connected. You cannot reuse a client.
at Client._connect (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\pg\lib\client.js:91:17)
at C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\pg\lib\client.js:310:10
at new Promise (<anonymous>)
at Client.connect (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\pg\lib\client.js:309:10)
at Object.module.exports.findUserById (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\database\register_sql.js:8:22)
at C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\routes\users.js:37:29
at Layer.handle [as handle_request] (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\route.js:137:13)
at next (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\route.js:131:14)
at Route.dispatch (C:\Users\Hasan\Desktop\Projeler\node-ogreniyorum\node_modules\express\lib\router\route.js:112:3)
I dont understand because I already end my client after I call my method.
register_sql.js :
module.exports.findUserById =(async (username) =>{
try {
await client.connect();
console.log('Connected successfuly');
const result = await client.query("select * from users where username = ($1)", [username]);
console.log(result.rows[0]['username']);
await client.end();
console.log('Client disconnected...');
} catch (err) {
console.log(err);
}
});
I call register_sql.js in users.js. Here is users.js :
const router = express.Router();
const registerSQL = require('../database/register_sql');
router.route('/register')
.get((req, res, next) => {
res.render('register');
})
.post((req, res, next) => {
const {
username,
password,
password2
} = req.body;
let errors = [];
if (!username || !password || !password2) {
errors.push("Please fill in all fields!");
}
if (password != password2) {
errors.push("Passwords do not match!");
}
if (password.length < 6) {
errors.push("Password has to be at least 6 characters!");
}
if (errors.length > 0) {
res.render('register', {
errors
});
} else {
registerSQL.findUserById(username);
res.redirect('/');
}
});
module.exports = router;
Thank you for helping!
With node-postgres (which is the one you're using) I've only made it work using the pool do manage the connections.
const pg = require('pg')
const pool = new pg.Pool();
pool.connect(function(err, client, done) {
if(err) {
return console.error('connexion error', err);
}
client.query("select * from users where username = ($1)", [username], function(err, result) {
// call `done()` to release the client back to the pool
done();
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0]['username'])
});
});
I had the same problem, dont create the new Client outside the function.
- const client = new pg.Client(connection);
-
function test() {
+ const client = new pg.Client(connection);
+
client.connect(err => {
if (err) {
console.log(err);
return;
}
client.query('select 123', [], (err, data) => {
if (err) {
console.log(err);
} else {
console.log('DATA:', data.rows[0]);
}
client.end();
});
});
}
I managed to fix this problem without using pool. Maybe that's not the most correct solution, but it works.
First create a separate js file, where you connect the client and export it:
const pg = require('pg')
const client = new pg.Client('your connection string')
client.connect()
module.exports = client
Then you just use the exported client, which has already been connected, so it won't reconnect again on each request. Be sure to import the client from the js file where you connect it.
const client = require('../db')
const register = async (req, res) => {
const {email, password, username} = req.body
const hashedPassword = await bcrypt.hash(password, 10)
const command = `insert into users(email, username, password, created) VALUES ('${email}', '${username}', '${hashedPassword}', current_timestamp)`
await client.query(command, (err, result) => {
err ? res.json({error: err.detail}) : res.json({message: 'User created!'})
})
}
well the problem occur because you haven't closed the connection to database.
Remember you have to close the connection before you sent something to client like that:
try {
await client.connect();
const result = await client.query(query, values);
await client.end();
res.status(201).send({
result,
});
} catch (err) {
return res.send({
error: err.detail,
message: "Can't create a new user, please check your info again!",
});
}
Pool approach is better practice but if someone want to connect with Client approach then this solution will work.
Code which will work with Client approach :
client.connect();
client.query(`select * from users where username = ($1)`, (err, result)=>{
try{
console.log("Test", result)
res.send(result)
} catch{
console.log("err", err)
res.status(500).json(err);
}
client.end();
})