store data from node.js to sql database - sql-server

I am trying to store result data received from client side into sql database, however I am getting these errors
TypeError: request.query(...).then is not a function
TypeError: callback is not a function
I am quite new to node.js and sql database. I spent quite a bit of time to figure these but not sure where to start,,
I tried to remove .then, it works fine but still throws 2nd error. Can anyone please advice on this problem?
node.js
//Receive from Angular Server
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all("/*", function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.listen(1433, function () { console.log('Example app listening on port 1433!') })
var sql = require('mssql');
var config = {
server: "",
database: "",
user: "",
password: "",
port:
};
app.post('/ping', function (req, res) {
res.send(res.body);
var jsondata = JSON.stringify(req.body);
var test = JSON.parse(jsondata);
var values = [];
values.push(test.GradeA, test.GradeB, test.GradeC)
console.log(values);
//values = [ '25', '36', '32' ]
var dbConn = new sql.Connection(config);
dbConn.connect().then(function () {
var transaction = new sql.Transaction(dbConn);
transaction.begin().then(function () {
var request = new sql.Request(transaction);
request.query("INSERT INTO RMS (GradeA, GradeB, GradeC) values VALUES ? ", [values])
.then(function () {
transaction.commit().then(function (recordSet) {
console.log('Rows Affected :' + request.rowsAffected);
dbConn.close();
}).catch(function (err) {
console.log("Error in Transaction Commit" + err);
dbConn.close();
});
}).catch(function (err) {
console.log("Error in Transaction Begin" + err);
dbConn.close();
});
}).catch(function (err) {
console.log(err);
dbConn.close();
});
}).catch(function (err) {
console.log(err);
});
});

request.query("INSERT INTO RMS (GradeA, GradeB, GradeC) values VALUES ? ", [values]) should be the line giving the error. It assumes the second parameter should be function. And when the second parameter is passed it does not return a promise and thus does not have then method.
mssql modules does not seem to support escaping in the way you are trying to do it. It support input method which can be used to inject data into query. From docs:
request
.input('input_parameter', sql.Int, value)
.query('select * from mytable where id = #input_parameter'

Related

Promise { <pending> } in node.js

I am trying to select items from sql server but I am getting below error. My SELECT statement right after completion on INSERT statement. What should I do to select properly without this error? Should I create separation connection?
Promise { }
node.js
//Receive from Angular Server
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const http = require('http');
var sql = require('mssql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all("/*", function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.listen(1433, function (err) {
if (err)
console.log(err);
else
console.log('Example app listening on port 1433!')
})
var config = {
};
app.post('/ping', function (req, res) {
res.send(res.body);
var jsondata = JSON.stringify(req.body);
var data = JSON.parse(jsondata);
sql.connect(config, function (err) {
if (err)
console.log(err);
else
console.log("Connection successful");
var request = new sql.Request();
request.input
.input('Loc', data.Location).input('ara', data.area)
.query('INSERT INTO Local_RMS (Location, Shift, PlanWld, ActualWld, OrWld, PlanPnt, ActualPnt, OrPnt, PlanAssy, OrAssy) VALUES (#Loc, #ara', (err, result) => {
if (err)
console.log(err);
else
console.log("Rows Affected : " + request.rowsAffected);
})
const result = request.query `SELECT * FROM Local_RMS WHERE DateCreated BETWEEN '11-24-2017 11:17:00' and '11-24-2017 11:18:59'`;
console.log(result); //error "Promise { <pending> }"
})
});

Mssql node, input value to request

I am using angular2 and mssql to connect to SQL Server.
This is my code
var express = require('express');
var app = express();
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'EnakAja123',
server: '192.168.1.37',
database: 'Angular'
};
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', false);
next();
});
app.post('/user', function (req, res) {
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.input('username', req.body.username) <<
request.input('password', req.body.password) <<
request.query('select * from Angular_user where username = #username and password = #password', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
How can I insert a value to this request.body.username and password?
Because I don't know how this request and response works
You should use body-parser with express to parse the request boy. Check body-parser documentation and example.

success function is not working angular

I am sending http request and when that request is finished I am trying to go to another state but the problem is it does not goes in the success callback I thought my be I'm getting an error so I wrote the error callback it does not goes in that to. Can anybody tell me what am I doing wrong
$scope.submitUpdatedData= function(user){
debugger;
// $http.post('/url',{params: value}).sucess(function(){
API.updateRecord(user).success(function(res){
$state.go('app' ,{} , {reload: true });
console.log("Hello");
});
}
The API code is given below. Here I invoke the http call
.factory('API', function($http) {
var api = {};
var baseURL = 'http://localhost:3000';
api.addRecord = function(record) {
console.log(record);
// $http.post(baseURL + '/addData', {name: record.name}.);
return $http.post(baseURL + '/addData', {rec:record});
};
api.deleteRecord = function(id){
return $http.get(baseURL +'/delete/' + id );
};
api.updateRecord = function(user){
return $http.post(baseURL + "/update/" ,{rec:user});
};
api.getAllRecord = function(){
return $http.get(baseURL+'/getAll');
};
api.getOneRecord = function(id){
return $http.get(baseURL + '/getOne/' + id)
};
return api;
})
UPDATE
I have replaced the .success part with then but it still not works
Second Update
This is my server side code
var express = require('express');
var mongoose = require('mongoose');
var util = require('util');
var bodyParser = require('body-parser')
var app = express();
var Schema = mongoose.Schema;
require('node-monkey').start({host: "127.0.0.1", port:"50500"});
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
};
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// app.use(express.json()); // to support JSON-encoded bodies
// app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(allowCrossDomain);
// app.use('/' , require('./index'))
mongoose.connect('mongodb://localhost:27017/myappdatabase');
var userSchema = new Schema({
name: String,
password: String
});
var Todo = mongoose.model('Todo', userSchema);
app.get('/getAll' , function(req, res){
Todo.find({} , function(err , todos){
if (err){
res.send(err);
}
console.log(todos);
res.send(todos);
});
});
app.get('/delete/:name' , function(req , res){
console.log(req.params);
console.log(req.params.name);
Todo.remove({
name : req.params.name
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
app.get('/getOne/:id' , function(req , res){
Todo.find({name : req.params.id}, function(err, todo) {
if (err)
res.send(err);
res.send (todo[0]);
// get and return all the todos after you create another
});
});
app.post('/update', function(req , res){
console.log(req.param('rec').name);
Todo.update({_id:req.param('rec').id} , {$set : {name:req.param('rec').name , password:req.param('rec').password}} , function(err){
if(err)
res.send("Error occured");
res.send("true");
});
});
app.post('/addData' , function(req , res){
console.log( req.param('rec').name);
var p = new Todo({name: req.param('rec').name , password: req.param('rec').password});
p.save(function(err){
if(err){
res.send(err);
console.log(error);
}
res.json(p);
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// module.exports = app;
Seems like success and error are deprecated, you should use then instead:
API.updateRecord(user).then(function(res){
$state.go('app' ,{} , {reload: true });
console.log("Hello");
});
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Source here
Seems like your request is never answered by the API Server. Maybe you can set a timeout for your request. Here it says you can do:
$http.post(url, data, {timeout: 100});
That should timeout your request after 100ms.

Trouble with MongoDB insert

Currently using MEAN in order to connect my AngularJS app to a database.
I have a button called "commit to database" that first clears the mongodb database, then inserts my array of data (stored in $scope.filterTable) into the database.
I then have a button called "load from database" that updates $scope.filtertable to match data from the database.
Half of the time when I click the "commit to database" button, my database is empty. Half of the time, it's filled with the data I expect it to have.
Anyone know what I'm doing wrong? Thanks!
Here's the code in my main AngularApp:
var commitToDatabase = function(){
deleteDatabase();
insertDatabase();
}
var insertDatabase = function(){
$http.post("/AngularApp", $scope.filterTable).success(function(response){
$http.get('/AngularApp').success(function(response) {
console.log(response);
});
});
}
var deleteDatabase = function(){
$http.delete('/AngularApp');
}
var loadFromDatabase = function(){
$http.get('/AngularApp').success(function(response) {
$scope.filterTable = response;
});
}
Here's the code in my server.js file:
var express = require("express");
var mongojs = require("mongojs");
var bodyParser = require("body-parser");
var app = express();
var db = mongojs("AngularApp", ["AngularApp"]);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/AngularApp', function (req, res) {
console.log('I received a GET request');
db.AngularApp.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/AngularApp', function (req, res) {
console.log("POST");
console.log(req.body);
db.AngularApp.insert(req.body, function(err, doc) {
res.json(doc);
});
});
app.delete('/AngularApp', function(req, res){
db.AngularApp.remove({},function(err, doc){
res.json(doc);
});
});
app.listen(3000);
console.log("Server running on point 30000");

LDAP Authentication with NodeJS, Express, and Passport-ldapauth

I"m having trouble authenticating to an Active Directory Server with the tools/applications mentioned in the title.
I'm using a test AD environment found here
Here are the relevant code snippets, if anyone has any suggestions I would really appreciate it.
Currently, the error i'm getting is "invalid username/password". I'm not sure if this is the bindDn account/pw or the one the user enters in the form. According to the passport-ldapauth project it's:
invalidCredentials flash message for InvalidCredentialsError
NoSuchObjectError, and
/no such user/i LDAP errors (default: 'Invalid username/password')
Thanks in advance.
CLIENT - auth.service.js
...
login: function(user, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.post('/auth/ldap', {
email: user.email,
password: user.password
}).
success(function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
deferred.resolve(data);
return cb();
}).
error(function(err) {
this.logout();
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
...
SERVER index.js
'use strict';
var express = require('express');
var passport = require('passport');
var auth = require('../auth.service');
var router = express.Router();
router.post('/', function(req, res, next) {
passport.authenticate('ldapauth', function (err, user, info) {
var error = err || info;
if (error) return res.json(401, error);
if (!user) return res.json(404, {message: 'Something went wrong, please try again.'});
var token = auth.signToken(user._id, user.role);
res.json({token: token});
})(req, res, next)
});
module.exports = router;
SERVER passport.js
var passport = require('passport');
var LdapStrategy = require('passport-ldapauth').Strategy;
exports.setup = function (User, config) {
passport.use(new LdapStrategy({
usernameField: 'email',
passwordField: 'password',
server: {
url: 'ldap://ldap.forumsys.com:389',
bindDn: "cn=read-only-admin,dc=example,dc=com",
bindCredentials: "password",
searchBase: 'ou=mathematicians,dc=example,dc=com',
searchFilter: 'uid={{username}}'
}
},
function (user, done) {
return done(null, user);
}
));
};
The problem is with the ou=mathematicians in the search base. There is the following mention in the comments on that web page:
The issue you are seeing is due to the fact that “uid=riemann” is a member of “ou=mathemeticians”, but does not reside under that ou. His membership in that ou is established by a uniqueMember attribute on “ou=mathemeticians”.
This should work (tried it even with ldapauth-fork which passport-ldapauth uses):
var opts = {
server: {
"url": "ldap://ldap.forumsys.com:389",
"adminDn": "cn=read-only-admin,dc=example,dc=com",
"adminPassword": "password",
"searchBase": "dc=example,dc=com",
"searchFilter": "(uid={{username}})",
}
};
For whose still lose your way, here is my code snippet in Typescript.
Server Side
import * as express from 'express'
import * as bodyParser from 'body-parser'
import * as cors from 'cors'
import * as passport from 'passport'
import * as ldapstrategy from 'passport-ldapauth'
// connect to LDAP server
const OPTS: ldapstrategy.Options = {
server: {
url: "ldap://ldap.forumsys.com",
bindDN: "cn=read-only-admin,dc=example,dc=com",
bindCredentials: 'password',
searchBase: "dc=example,dc=com",
searchFilter: "(uid={{username}})"
}
}
passport.use(new ldapstrategy(OPTS))
// instantiate the server
const app = express()
// parse the request data automatically
app.use(bodyParser.json())
// allow cross origin resource sharing
app.use(cors())
// inject LDAP connection to express server
app.use(passport.initialize())
// listen to port defined
const port = process.env.PORT || 8085
app.listen(port, (): void => {
console.log(`Listening on port ${port}`)
})
app.post('/login', (req: express.Request, res: express.Response, next: express.NextFunction): void | Response => {
passport.authenticate('ldapauth', (err, user, info): void => {
var error = err || info
if (error)
res.send({
status: 500,
data: error
})
if (!user)
res.send({
status: 404,
data: "User Not Found"
})
else
res.send({
status: 200,
data: user
})
})(req, res, next)
})
Client Side
Your code looks correct, but the error you're getting leads me to believe you really don't have the correct username/password supplied! Are you sure you're testing with the right credentials?
As a sidenote -- if you're looking for a simpler way to do this for a big project, and don't mind spending some money, Stormpath's API service does this sort of thing for you: it basically syncs your AD / LDAP users into it's API service so you can work with them via a REST API (it's much simpler).
There are two libraries you can use to work with it:
express-stormpath
passport-stormpath
Both are pretty simple / nice to use.
this code me
phpLDAPadmin express.js and passport-ldapauth
var express = require('express'),
passport = require('passport'),
LdapStrategy = require('passport-ldapauth');
const OPTS = {
server: {
url: 'ldap://localhost:389',
bindDN: 'cn=admin,dc=ramhlocal,dc=com',
bindCredentials: 'password',
searchBase: 'dc=ramhlocal,dc=com',
searchFilter: '(uid={{username}})'
}
};
var app = express();
passport.use(new LdapStrategy(OPTS));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(passport.initialize());
app.post('/login', function (req, res, next){
passport.authenticate('ldapauth', {session: false}, function(err, user, info) {
var error = err || info
console.log(user);
if (error)
res.send({
status: 500,
data: error
})
if (! user) {
res.send({
status: 404,
data: "User Not Found"
})
}
res.send({
status: 200,
data: user
})
})(req, res,next)
})
app.listen(8080);
enter image description here

Resources