Promise { <pending> } in node.js - sql-server

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> }"
})
});

Related

store data from node.js to sql database

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'

Cannot POST /api/register in Node Js

I am new at here and I am getting Can not post /api/register error in postman and 404 not found in console, I have checked all the possible question answers. Please assist me as soon as possible.
Thanks in advance.
The auth.controller.js file
var express = require ('express'); //EXPRESS Package
var route = express.Router(); //define our app using express
// var userModel = require('../model/user.model');
// var session = require('express-session');
var bodyParser = require('body-parser');// get body-parser
route.use(bodyParser.json()); // for parsing application/json
route.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
/**
*
* Register user
*/
route.post('/api/register', function (req, res) {
console.log(req.body);//res.sendStatus(200);
// userModel.create(req.body).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
/**
*
* Login user
*/
route.post('/api/login', function (req, res) {
// userModel.authenticate(req.body.email, req.body.password).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
module.exports = route;
=========================================================================
The server.js File
var express = require ('express'); //EXPRESS Package
var app = express(); //define our app using express
var cors = require('cors');
var session = require('express-session');
var bodyParser = require('body-parser');// get body-parser
// var morgan = require('morgan'); //use to see requests
// var assert = require('assert');
// var path = require('path');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cors());
/**
* Header Control
*/
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH");
res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
next();
} );
//routes
app.use('/api/register', require('./controllers/auth.controller'));
app.use('/api/login', require('./controllers/auth.controller'));
// app.use('/api/users', require('./controllers/users.controller'));
// app.get('/api', function (req, res) {
// res.send('/api/login');
// } );
// start server
var server = app.listen(8001, 'localhost', function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
// module.exports = app;
When you use
app.use('/api/register', require('./controllers/auth.controller'));
Your application routes everything that comes to /api/register into require('./controllers/auth.controller'). Then require('./controllers/auth.controller') checks the remainder of the url for /api/register or /api/login, routes the request to the respective middleware if your router gets a match.
In other words, you need to post to /api/register/api/register in order to reach your desired middleware.
For a quick solution:
You should delete
app.use('/api/register', require('./controllers/auth.controller'));
app.use('/api/login', require('./controllers/auth.controller'));
and replace it with:
app.use('/', require('./controllers/auth.controller'));
For a better one:
You should delete
app.use('/api/register', require('./controllers/auth.controller'));
app.use('/api/login', require('./controllers/auth.controller'));
and replace it with:
app.use('/api', require('./controllers/auth.controller'));
in your app.js and also in your auth.controller.js you should replace:
route.post('/api/register', function (req, res) {
console.log(req.body);//res.sendStatus(200);
// userModel.create(req.body).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
/**
*
* Login user
*/
route.post('/api/login', function (req, res) {
// userModel.authenticate(req.body.email, req.body.password).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
with:
route.post('/register', function (req, res) {
console.log(req.body);//res.sendStatus(200);
// userModel.create(req.body).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
/**
*
* Login user
*/
route.post('/login', function (req, res) {
// userModel.authenticate(req.body.email, req.body.password).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});

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.

How to add a new object with AngularJS and mongoDB

I'm using NodeJS, ANgularJS, and MongoDB with mongoose to make a website. I'm having some trouble adding an object in mongoDB. The name of the object is Todo.
Here are the models of Todo:
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
password : String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema);
In the controller I create a new Todo and push it
angular.module('app').controller('Connexion', ['$scope', 'Todos','$location', function($scope,Todos, $location) {
$scope.editing = [];
$scope.todos = Todos.query();
$scope.save = function() {
var todo = new Todos({ name: "test", password: "test", completed: false });
$scope.todos.push(todo);
Todos.save($scope.todo);
}
}]);
This is my html page, each time I click on the button I Have a new todo created and it's displayed on screen:
<button ng-click="save()">Creer POST </button>
<ul>
<li ng-repeat="todo in todos">
{{todo.name}}
{{todo.password}}
</li>
</ul>
But I have a problem, the new object is not added on the database. How can I do it?
This is my files in the back-end :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. */
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos */
router.post('/', function(req, res, next) {
Todo.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id */
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
And if this can help this the back-end file app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var Post = require('./models/Post.js');
var routes = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', function(req, res, next){
res.sendFile(__dirname + '/public/index.html');
});
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
module.exports = app;
$scope.todo from Todos.save($scope.todo); is not defined so this is why you might not manage to save anything

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.

Resources