I'm trying to insert data into a 'users' table inside a postgresql database using the 'pg' NPM module.
But when I make a POST request, the transaction executes indefinitely without terminating and with no response.
I can't seem to locate where the problem is?
I've checked the database settings and everything seems fine.
Could you please help me spot where the problem is with the code?
Thanks in advance!
index.js (main server):
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
const db = require('./queries')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.post('/users', db.createUser);
app.listen(port, () => {
console.log(`App running on port ${port}.`)
});
queries.js (Script for querying the database):
const Pool = require('pg').Pool;
const pool = new Pool({
host: 'localhost',
user: 'travel',
password: '12345',
database: 'try',
port:5432,
});
const createUser = (request, response) => {
const { name, email } = request.body
pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
if (error) {
throw error
}
response.status(201).send(`User added with ID: ${result.insertId}`)
})
}
module.exports = {
createUser,
}
Database query for creating 'users' table:
CREATE TABLE IF NOT EXISTS users
(
id SERIAL PRIMARY KEY NOT NULL,
email varchar(255) NOT NULL,
name varchar(255) NOT NULL
);
at first when you want to use database you must be connect to database
const { Client } = require("pg")
const config = require("../config")
const client = new Client(config.databse)
client.connect()
module.exports = client
and in your client and pg are almost similar
Related
I am trying to connect to PostgreSQL database via express.js with the following codes.
db.js:-
const Pool = require('pg').Pool;
const pool = new Pool({
user: "samar",
password: "qwer",
host: "localhost",
port: 5432,
database: "samar",
connectionLimit : 10
})
module.exports = 'pool';
index.js:-
const express = require('express');
const cors = require("cors");
const app = express();
var pool = require("./db").pool;
//middleware
app.use(cors());
app.use(express.json())
//routes
//create todo
app.post('/todos', async (req, res) => {
try{
const {description} = req.body;
const newTodo = await pool.query(
"INSERT INTO todo (description) VALUES($1) RETURNING *",
[description]
);
res.json(newTodo.rows[0]);
}
catch(err){console.error(err.message)}
})
app.listen(2000,()=>{
console.log('server is running on port 2000');
})
But I am getting an error as Cannot read property 'query' of undefined when I am sending
{
"description": "Hello World"
}
as POST request from postman to http://localhost:2000/todos. Please guide me through this error.
I have two files. I use Node.js with PostgreSQL. In the first scenario in the index.js I receive an empty object (so db = {}), however, in the second scenario I receive the wanted query function.
And, of course, db.query() doesn't work in the first scenario, but it works charmly in the second one.
If I rename the db to pool in the index.js, it still doesn't work, I get the same problem that the required variable is {} and does not have any query function.
Why does this happen and what happens in under hood?
First scenario:
db.js:
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'postgres',
password: 'password',
host: 'localhost',
port: 5432,
database: 'perntodo',
});
module.export = pool;
Second scenario:
db.js:
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'postgres',
password: 'password',
host: 'localhost',
port: 5432,
database: 'perntodo',
});
module.exports = {
query: (text, params) => pool.query(text, params),
};
The index.js in both scenario:
const express = require('express');
const app = express();
const cors = require('cors');
const db = require('./db');
console.log('db:', db);
// middleware
app.use(cors());
app.use(express.json());
// create a todo
app.post('/todos', async (req, res) => {
try {
const { description } = req.body;
const newTodo = await db.query(
'INSERT INTO todo (description) VALUES($1)',
[description],
(err, res) => {
if (err) return next(err);
}
);
res.json(newTodo);
} catch (err) {
console.error(err);
}
});
app.listen(5000, () => {
console.log('Server has started on port 5000.');
});
Output:
First scenario:
db {}
Second scenario:
db { query: [Function: query] }
It was a very silly mistake, I will leave the post here so maybe it will help others in the future as well.
I wrote module.export instead of module.exports.
I'm trying to create this API with NodeJS, Express and Mysql but when testing on Postman, while the code is working to update the values on the database, it doesn't read the info I insert in the body of the request. For example, I can access the params info (codAluno), but not the request body (Empresa_Atual).
I have two files for the API: routes.js and index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./routes')
const port = 3000
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(bodyParser.json())
app.get('/', (request, response) => {
response.json({ info: 'API' })
})
app.get('/alunos', db.getAlunos)
app.get('/alunos/:id', db.getAlunoByCod)
app.post('/alunos/:id',db.updateAluno)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
and routes.js
const mysql = require('mysql');
// Set database connection credentials
const config = {
host: 'localhost',
user: 'user',
password: '',
database: 'student',
};
// Create a MySQL pool
const pool = mysql.createPool(config);
const updateAluno = (request, response) => {
const codAluno = parseInt(request.params.id)
var Empresa_Atual = request.body.Empresa_Atual
pool.query('UPDATE aluno SET `Empresa_Atual`= ? WHERE `codAluno` = ?', [Empresa_Atual, codAluno], (error, result) => {
if (error) throw error;
response.send('User updated successfully.');
});
}
This is the request I'm sending via postman
For example, the variable Empresa_Atual is always null even though I assigned it to the request body.
Can anyone help?
Thanks!
I had the same problem. I had the following: req.params.id. I then changed it to req.params['id'] and it started working. Apparently, the req.params was an object instead of a single value.
Im making an API to insert data into my PostgreSQL database hosted at Azure, I have disable SSL and added firewall exceptions in order to secure the conexion, but Im still having an Authentication error when trying to make a POST request, this is the error log:
I think all the credentials I have to provide are in correct:
This is the code of the API:
Am I missing something? Some light would be apreciate.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
user: "LuisFulcrum#sensors",
host: "sensors.postgres.database.azure.com",
database: "postgres",
password: "notTheRealPassword",
port: 5432
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.listen(8000, () => {
console.log(`Server is running, listening to port 8000`);
});
app.post("/api/v1/nodo2059e7", (req, res) => {
const { label, status, priority } = req.body;
pool.query(
"INSERT INTO nodo2059e7(fecha, temperatura, humedad, presionatmosferica, pm1, pm2, pm10) VALUES (NOW(),1 ,1 ,1 ,1 ,1, 1);",
[label, status, priority],
(error, results) => {
if (error) {
throw error;
}
res.sendStatus(201);
}
);
});
Seems the error is obvious that you provided the wrong password. I also tested your code on my side using my on Azure Postgres SQL:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
user: "mgr#stanpgtest",
host: "stanpgtest.postgres.database.azure.com",
database: "my db name",
password: "my pass",
port: 5432
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.listen(8000, () => {
console.log(`Server is running, listening to port 8000`);
});
app.post("/api/v1/nodo2059e7", (req, res) => {
const { label, status, priority } = req.body;
pool.query(
"select now()",
(error, results) => {
if (error) {
throw error;
}
res.send(results);
}
);
});
everything works as excepted :
Just try to reset your password on Azure portal and try again:
I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values
router.put('/special/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: {email: req.body.email, password: req.body.password}
},
{
new: true,
useFindAndModify: false
},
function(err, updatedData) {
if(err) {
res.send('Error updating');
} else {
res.json(updatedData);
}
});
});
Try rewriting it using async, and make sure your Mongoose schema is correct as well.
So your mongoose model should be a seperate file called 'userModel.js'.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema ({
email: String,
password: String,
});
let User = module.exports = mongoose.model('User', userSchema);
Then in your app.js.
Have:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');
//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection
db.once('open', function() {
console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
console.log(err);
})
//Starting App (on localhost:3000)
app.listen(port, function() {
console.log('Server started on port ' + port);
});
Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:
mongod
This should work, and if its already running you should see a message at the bottom saying:
2019-07-19T12:17:37.716+1000 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.
Note: Before the route, you need to require your model so mongoose can update records for you.
//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){
const id = req.params.id
//Making a user object to parse to the update function
let updatedUser = {}
updatedUser.email = req.body.email
updatedUser.password = req.body.password
await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
if(err){
console.log(err)
}
else {
console.log(updatedData)
//res.redirect or res.send whatever you want to do
}
})
})