Mssql node, input value to request - sql-server

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.

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'

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

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

Error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Using expressjs and angular

I think so many people gave solution on it but none of them worked for me
Please check my code and tell me where I have gone wrong...
I deployed in heroku also still seeing the same issue
Angular JS snippet:
$http({
method: 'GET',
url: "https://api.forecast.io/forecast/2c56930e3e0117b9943b9f618acfe981/17.3434321,78.536526",
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}).
success(function(status) {
$scope.weather = status.data;
}).
error(function(status) {
console.log("failure");
});
Expressjs(server) snippet:
var express = require('express'),
http = require('http');
var bodyParser = require('body-parser');
var jsonfile = require('jsonfile');
var path = require('path');
var cors = require('cors');
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'api.openweathermap.org');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
var app = express()
.use(bodyParser.urlencoded({
extended: true
}))
.use(bodyParser.json())
.use(express.static(__dirname + '/public'))
.use(cors())
.use(allowCrossDomain)
.use('/node_modules', express.static(__dirname + '/node_modules'))
.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
You dont need the "Access-Control-Allow-Origin" settings.
The problem is, that your are grabbing the url from the client side.
Just make a route with nodejs (maybe with express) to get the data from an extern server.
Than you can get your data through your nodejs route to show/use it on client side (angularjs).
Update:
Server side:
var express = require('express'),
http = require('http');
var bodyParser = require('body-parser');
var app = express();
var request = require('request');
app
// express json parser
.use(bodyParser.urlencoded({
extended: true
}))
.use(bodyParser.json())
// public foder for client side
.use(express.static(__dirname + '/public'))
// express route to get the forecast data/json
.get('/forecast', function(req, res) {
request({
url: "https://api.forecast.io/forecast/2c56930e3e0117b9943b9f618acfe981/17.3434321,78.536526"
}, function (error, response, body) {
res.send(response.body);
});
})
// server port
.listen(8080);
On Clientside you have to call now the url of your local route:
$http
.get("http://localhost:8080/forecast")
.success(function (data, status) {
$scope.weather = data;
})
.error(function (data, status) {
console.log("Request failed " + status);
})
.then(function() {
console.log($scope.weather);
});

Sending SMS via Twilio POST error

This comes after half a day of banging my head against the screen, so any help would be greatly appreciated.
I'm trying to send an SMS message via Twillio on a click-event. I'm using Angular, calling the SendTestMessage function on click. Unfortunately, I keep running into this error:
POST http://localhost:3000/sendsms 500 (Internal Server Error)
Here is my controller:
.controller('WhotoMessageCtrl', function($scope, UserService, $http, $q){
console.log("whotomessage page");
$scope.saveContactInfo = saveContactInfo;
$scope.contact = {};
$scope.sendTestMessage = sendTestMessage;
function sendTestMessage(number){
console.log('this fired', number);
var defer = $q.defer();
$http({
url: '/sendsms',
method: 'POST',
data: JSON.stringify({number}),
contentType: 'application/json',
}).success(function (number){
console.log('text has been sent to', number);
defer.resolve(user);
});
return defer.promise;
};
Here is my server side code:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
if ('OPTIONS' == req.method){
return res.send(200);
}
next();
});
app.use(function (req, res, next) {
var sendSMS = function(to){
var outgoing = {};
outgoing.to = to;
outgoing.from = '19725593683';
outgoing.body = 'Your table is ready';
client.messages.create(outgoing, function(error, message){
if (error){console.log(error.message)}
})
};
app.post('/sendsms', function(req, res){
sendResponse(res, req.body.phoneNo, 201)
sendSMS(req.body.phoneNo)
res.end();
});
Any suggestions?
Hey Twilio developer evangelist here.
It could have been that you forgot to copy bits of the code, but it seems client hasn't been defined, which means you aren't even making a request to Twilio.
The correct way to initialise client according to the documentation is:
// Your accountSid and authToken from twilio.com/user/account
var accountSid = '{{ account_sid }}';
var authToken = "{{ auth_token }}";
var client = require('twilio')(accountSid, authToken);
Only then you can on your code do:
var sendSMS = function(to){
var outgoing = {};
outgoing.to = to;
outgoing.from = '19725593683';
outgoing.body = 'Your table is ready';
client.messages.create(outgoing, function(error, message){
if (error){console.log(error.message)}
})
};
Hope this helps you!

Resources