Azure SQL database is not updating with data - sql

I have created a nodejs azure web app and it is running perfectly fine,
Now I want to get my post data to azure MS SQL DB, I have created a code for that, however sql db is not updating with POST data, can anyone help me with this.
var express = require('express');
var bodyParser = require('body-parser');
var sql = require('mssql');
var port = 8080;
var app = express();`enter code here`
var path = require('path');
//CORS Middleware
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,OPTIONS");
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,contentType,Content-Type,Accept,Authorization");
next();
});
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
//setup database connection
var dbconfig = {
user:"username",
password:"password",
server : "server_name",
database: "db_name"
};
// ConnectionPool
//connect to the database
var executeQuery = function(res,query){
sql.connect(dbconfig,function(err){
if(err){
console.log("there is a database connection error -> "+err);
res.send(err);
}
else{
// create request object
var request = new sql.Request();
// query to the database
request.query(query,function(err,result){
if(err){
console.log("error while querying database -> "+err);
res.send(err);
}
else{
res.send(result);
sql.close();
}
});
}
});
}
app.get('/', function(req, res){
res.render('index', {
title: 'Hello World',
showTitle:true,
people: ['John', 'Steve', 'Jose']
});
});
app.get('/index', function(req, res){
res.render('index');
});
app.get('/contact', function(req, res){
res.render('contact');
});
app.post('/my_user', function(req, res){
//return res.send(req.body);
console.log(req.body.email + ' and ' + req.body.mobile);
var parameters = [
{ name: 'email', sqltype: sql.NVarChar, value: req.body.email},
{ name: 'mobile', sqltype: sql.NInt, value: req.body.mobile},
{ name: 'msg', sqltype: sql.NVarChar, value: req.body.msg},
];
var query = "insert into forMyCV values(#email, #mobile, #msg);";
executeQuery (res, query, parameters);
return res.redirect('/');
});
app.listen(port);
console.log('Server started on port '+port);
can anyone help me with this explain this to me. why this is happening

I'm afraid there are two issues in your code after I had test it.
According to the tab Connection strings of your Azure SQL Database on Azure portal as the figure below, there is a required parameter encrypt=true in the connection string like for JDBC and others, too.
So the correct config for Azure SQL Database using mssql should be as below.
const config = {
user: '<your username>#<your sql server name>',
password: '<your password>',
server: '<your sql server name>.database.windows.net', // You can use 'localhost\\instance' to connect to named instance
database: '<your database name>',
options: {
encrypt: true // Use this if you're on Windows Azure
}
}
The required options: {encrypt: true} property can not be ignored. Otherwise, it will cause the error.
there is a database connection error -> ConnectionError: Server requires encryption, set 'encrypt' config option to true.
(node:665784) UnhandledPromiseRejectionWarning: ReferenceError: res is not defined
at D:\projects\node\express-demo\mssql-query-demo.js:43:13
at _poolCreate.then.catch.err (D:\projects\node\express-demo\node_modules\mssql\lib\base.js:287:7)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:665784) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:665784) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
the executeQuery function is defined with two parameters res and query, but it be used with three parameters executeQuery (res, query, parameters); in the callback function(req, res) of app.post('/my_user'). It will not cause any error and just ignore the nonmatched last parameter parameters.
Hope it helps.
Update: Redefine the executeQuery function as below.
var executeQuery = function(res,query, parameters){
sql.connect(dbconfig,function(err){
if(err){
console.log("there is a database connection error -> "+err);
res.send(err);
}
else{
// create request object
var request = new sql.Request();
// query to the database
parameters.map(item => {
request.input(item.name, item.sqltype, item.value);
})
request.query(query,function(err,result){
if(err){
console.log("error while querying database -> "+err);
res.send(err);
}
else{
res.send(result);
sql.close();
}
});
}
});
}

Related

How to fix [Error: Network Error] calling localhost api using react native and express js

I'am currently studying React native and Express JS for my server side. So now I do practicing calling api from express js to react native and I use axios to call http request. My problem is in my cmd it shows that [Error: Network Error]. To be more specific I will show you guys my sample work both server.js and components and sample screenshot Error on my cmd.
[Error: Network Error]
Server JS:
const express = require('express');
var cors = require('cors')
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : '192.168.61.1',
user : 'root',
password : '',
database : 'sample_db'
});
if(connection) {
console.log(connection);
}
// Starting our app.
const app = express();
var cors = require('cors');
app.use(cors());
// Creating a GET route that returns data from the 'mobile' table.
app.get('/api/readings', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'mobile' table).
connection.query('SELECT * FROM tbl_mobile', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// get the specific meter
app.get('/api/readings/:id', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'mobile' table).
connection.query('SELECT * FROM tbl_mobile WHERE id = ?',req.params.id, function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('http://192.168.61.1/api/readings');
});
Axios:
axios.get('http://192.168.61.1:3000/api/readings')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
Response:

Azure functions: Exception: TypeError: connection.query is not a function

I have a simple Azure function trying to get all data from a SQL table. The connection is successful and I can connect to the database, but whenever I run the get request, I end up with an error
Exception: TypeError: connection.query is not a function
Stack: TypeError: connection.query is not a function
This is the line throwing the error
connection.query(query, (err, results, fields) => {
this is my index.js azure get function
const express = require('express')
const bodyParser = require('body-parser')
let connection = require('../configs/dbConfig')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
module.exports = async function (context, req, res) {
const query = 'SELECT * FROM entrys'
connection.query(query, (err, results, fields) => {
if (err) {
const response = { data: null, message: err.message, }
res.send(response)
}
const pokemons = [...results]
const response = {
data: pokemons,
message: 'All entrys successfully retrieved.',
}
res.send(response)
})
}
Am using tedious as the connection driver. my dbconfig
let Connection = require('tedious').Connection;
let pool = {
server: "localhost", // or "localhost"
authentication: {
type: "default",
options: {
userName: "sa",
password: "root",
}
},
options: {
database: "testing",
encrypt: false
}
};
var connection = new Connection(pool);
connection.on('connect',function(err){
if(err){
console.log('Connection Failed');
throw err;
}
else{
console.log('Connected');
}
});
module.exports = connection
what am I doing wrong, thank you in advance
You should use Request to query.
In the official documentation, I did not see the usage of connection.query. It is not recommended that you use tedious when you are not very familiar with it. I have a sample code here, I hope it helps you.
You can download my Sample Code which use mssql package.
var express = require('express');
var router = express.Router();
let connection = require('../configs/dbConfig')
var Request = require('tedious').Request;
/* GET users listing. */
router.get('/', function(req, res, next) {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
res.send('respond with a resource');
});
module.exports = router;
Test Result:

Consume web service in Node.js and bulk insert to Oracle Database

I need to consume third party webservice using node js and write it to oracle table . Basically I got the code for getting the data. What is the command to insert bulk data into oracle from node json? I will be getting a huge file and I am parsing it. The code is as below.
Can someone help me with insert command here?
const express = require("express");
const oracledb = require("oracledb");
const cors = require("cors");
const bodyparser = require("body-parser");
const request = require("request");
let app = express();
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.get("/demo",(req,res)=>{
oracledb.getConnection({
user:"INFO",
password:"12345",
connectString:"194.234.222.22:1521/TEST"
},(err,connection)=>{
if(err) throw err;
else{
//make request call
try{
request.post({
url: 'https://qmilet.com/api/v1/partners/login',
body: {"user":"_api","password":"_api"},
json: true
}, function(error, response, body){
//console.log(body);
token = body.access_token
console.log(token);
//make api request
//31ae0b786d4958c0a93a459f46a59d67b8a9cff8
try{
//replace thw dynamic token
//Syntax : ${token}
request.post({
url : `https://qmilet.com/api/v1/orders/pull?access_token=${token}&date_from=2020-05-01&date_to=2021-05-30&include_synced=1`
},function(err,response,body){
let obj = JSON.parse(body);
res.send(obj.data);
//how to read parsed data, and insert into oracle db
})
}catch(err){
console.log(err);
}
});
}catch(err){
console.log(err);
}
}
});
});
app.listen(8080,()=>{
console.log("server started");
});
I am using 12.1.0.2 version of Oracle.

Can't Post data from postman to database with express

I am unable to Post data from postman to mysql database
I'm using express
I have tried using Body and Raw x-wwww-form-urlencoded
Here is my code (Yes everything is in the same file I know it's not a good thing I'm sorry)
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// connection configurations
var dbConn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'testexpress'
});
// connect to database
dbConn.connect();
// Add a new user
app.post('/user', function (req, res) {
let user = req.body.user;
if (!user) {
return res.status(400).send({ error:true, message: 'Please provide user' });
}
dbConn.query("INSERT INTO users SET ? ", { user: user }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
});
});
// set port
app.listen(3000, function () {
console.log('Node app is running on port 3000');
});
module.exports = app;
here is my screenshot error from Postman and my database
Modify your code like this. It should work
// Add a new user
app.post('/user', function (req, res) {
let user = [req.body]
console.log(user);
if (!user) {
return res.status(400).send({ error:true, message: 'Please provide user' });
}
dbConn.query("INSERT INTO users SET ? ", user, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
});
});
Your code is showing this error message error:true, message: 'Please provide user because everytime in your code the condition if (!user) is executed, because let user = req.body.user is going to give undefined value so you are going to get that error and the rest of the code will never execute then
.

res.json() won't work when trying to display data

I am using Nodejs, express, and postgresql to create a rest api. This is my first time doing any of this so I apologize for the noobness. I have been just testing this out and seemed to be about to get retrieve information from a database locally but when I try to send the data with res.json() nothing shows up. Here is the code I have so far.
var express = require('express');
var client = new pg.Client({user: 'xxx', password: 'xxx', database: 'xxx', host: 'xxx'});
var app = express();
app.get('/test1', function(req,res){
var name;
client.connect(function(err){
if(err){
return console.error('could not connect to postgres', err);
}
client.query("select classname from class", function(err, result){
if(err){
return console.error('error running query', err);
}
name = result.rows[0].classname;
console.log(name);
client.end();
});
});
res.send(name);
});
I used the console log and it printed out what I needed but for some strange reason it won't send. Thanks for the help! Also, if you see anything else wrong don't be afraid to say it. Thanks!
It's an asynchronous function so it would go like this:
var express = require('express');
var client = new pg.Client({
user: 'xxx',
password: 'xxx',
database: 'xxx',
host: 'xxx'
});
var app = express();
app.get('/test1', function(req, res) {
var name;
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgres', err);
}
client.query("select classname from class", function(err, result) {
if (err) {
return console.error('error running query', err);
}
name = result.rows[0].classname;
console.log(name);
client.end();
res.send(name);
});
});
});
What is happening in your code is that you are sending before the query is done executing. You can see it on the console because your log statement is correctly executing after the query.
Also you should take care of your errors as well - so instead of returning do another res.send (or res.json) with some error mesg.