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:
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'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
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 trying to put together a simple website, but when trying to insert to my Heroku database it says my relation (table) does not exist but in fact exists!!..I connect through database_url provided by Heroku and when I connect through my command line and insert new rows, they get added and I can see their table and data but when I try to insert the data everytime I hit summit in the form, the error pops up like there were no table with that name..
const express = require('express');
app = express();
require('dotenv').config()
var sslRedirect = require("heroku-ssl-redirect").default;
var compression = require('compression');
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
})
//MIDDLEWARE
app.set("port",process.env.PORT || 3000);
app.set("view engine", "ejs");
app.use(sslRedirect());
app.disable('x-powered-by');
app.use(compression());
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended:false
})
);
app.use
const errorController = require('./controllers/errorController');
//const middleware = require('./controllers/middleware')
//ROUTES
app.get('/',(req,res,next) => {
res.render('test')
});
app.post('/thanks', async (req, res) => {
data = {
name : req.body.name,
email : req.body.email,
service: req.body.service,
message: req.body.message};
const text ='INSERT INTO customers(name,email,service,message) VALUES($1, 2$, 3$, 4$) RETURNING *;'
const values = [data.name, data.email, data.service, data.message];
client.connect()
try {
const res = await client.query(`INSERT INTO customers (name,email,service,message) VALUES(${data.name},${data.email},${data.service},${data.message}) RETURNING *;`);
console.log(res.row[1])
client.end()
}catch (err) {
console.log(err.stack)
client.end()
}
res.render('thanks')
})
app.get('/contact',(req,res) => {
res.render('contact')
})
app.get("/services" , (req,res) => {
res.render('services')
})
app.get("/about" , (req,res) => {
res.render("about")
})
app.get('/maysspabeauty.com/contact/*' , (req , res) => {
res.render('contact')
})
app.use(errorController.pageNotFoundError);
app.use(errorController.internalServerError)
app.listen(app.get("port"), () => {
console.log(`server running at http://localhost:${app.get("port")}`);
});
here is screenshot of the errorerror image
Solved this.... seems my problem was just that i was using heroku hobby-dynos and they are NOT meant to be used in production....after i upgraded the dynos, it just throw me this error (no pg_hba.conf entry for host) which i fixed just using ssl"{
ssl:
rejectUnauthorized:false
};
index.js
const { Client } =require('pg');
const client = new Client ({
user: 'postgres',
host: 'localhost',
database: 'test',
password: 'admin',
port: 5432,
});
client.connect();
module.exports.myconnection = client;
app.js
const express = require("express");
const port = 3000;
const app =express();
const db =require("./db");
app.use(express.json());
const interactrouter = require("./routes/interactions");
app.use("/data",interactrouter);
app.listen(port, () =>
console.log(`Server running at http://localhost:${port}`) // not single cotaions above tab
);
interactions.js
const express = require ('express')
const router = express.Router()
const db =require('../db')
const { Client } = require('pg')
const client = new Client()
router.get('/',(req,res) => {
client.query("SELECT id, decription, drugcode, diseasecode, type FROM interactions;")
.then (rows =>{
console.log(rows);
res.json(rows)
})
.catch(error => {
console.log(error)
})
})
module.exports =router;
my problem I connect to the server but I can't get the data from the database and this is my code how can I fix it thank you all
so how can I fix it or what I should edit I'm new in this field