I am trying to insert the sensor data into a SQL Server database. I have tried all the possible way to insert the incoming data into database, but I failed. I am new to Nodejs and I really have no idea why these errors are occurred during executing process. It would be great if anyone could help me.
Thank you in advance.
The error I get is:
TypeError: Cannot read property 'writeHead' of undefined.
function addData (req, resp, reqBody, data)
{
try {
if (!reqBody) throw new Error("Input not valid");
data = JSON.parse(reqBody);
//reqBody = JSON.parse(data);
if (data) {//add more validations if necessary
var sql = "INSERT INTO arduinoData (Machine, StartTime, EndTime, LengthTime) VALUES ";
sql += util.format("(%s, '%s', %s, %s) ", data.Machine, data.StartTime, data.EndTime, data.LengthTime);
db.executeSql(sql, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.send200(req, resp);
}
});
}
else {
throw new Error("Input not valid");
}
}
catch (ex) {
httpMsgs.show500(req, resp, ex);
}
};
function sendBackupData()
{
var jsonTable = { "table": [] };
fs.readFile("backup.json", "utf8", function (err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
if (jsonTable.table.length == 0) {
return;
}
for (var index = 0; index < jsonTable.table.length; index++) {
var options = {
url: serverURL,
method: "POST",
form: jsonTable.table.shift()
};
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent backup message!");
} else {
console.log('Error: ' + error);
console.log("CANT'T SEND BACK");
console.log(options.form);
jsonTable.table.push(options.form);
}
});
}
var outputJSON = JSON.stringify(jsonTable);
console.log(outputJSON);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
console.log("Sent backup data!");
});
});
}
function getTime()
{
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
// Unix Time
var unixTime = Math.floor(date / 1000);
// Check if it is day or night
var isDay;
if (date.getHours() >= 8 & date.getHours() < 16)
{
isDay = true;
}
else
{
isDay = false;
}
return [year + '-' + month + '-' + day, hour + ':' + minute + ':' + second, unixTime, isDay];
}
/*
--- Main Code ---
*/
function vibrationStart()
{
/*
Should get:
- Start time and date the vibration started
- Whether it was day or night
Will send the message, if there is network connection, once complete.
Will store message into a JSON file if there is no network connection.
*/
var jsonTable = { "table": [] };
var startTime = getTime();
console.log(startTime[0] + " " + startTime[1]);
var startData = {
machine: machineName,
start_time: startTime[0] + " " + startTime[1],
day_night: startTime[3],
active: "true"
};
const options = {
url: serverURL,
method: "POST",
form: startData
};
var reqBody = [{
Machine : "",
StartTime : ""
}];
reqBody.push({"Machine" : startData.machine,"StartTime" : startData.start_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent starting message!");
sendBackupData();
addData();
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(startData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
return startTime[2];
}
function vibrationStop(startTimeUnix)
{
var jsonTable = { "table": [] };
var endTime = getTime();
console.log(endTime[0] + " " + endTime[1]);
var endTimeUnix = endTime[2];
var lengthTime = endTimeUnix - startTimeUnix;
console.log("Length time: " + lengthTime);
var endData = {
machine: machineName,
end_time: endTime[0] + " " + endTime[1],
length_time: lengthTime,
active: "false"
};
const options = {
url: serverURL,
method: "POST",
form: endData
};
var reqBody = [{
EndTime : "",
LengthTime :"",
}];
reqBody.push({"EndTime" : endData.end_time,"LengthTime" : endData.length_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent end message!");
sendBackupData();
addData()
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(endData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
}
http.createServer(function (req, resp) {
app.get('/', addData);
}).listen(settings.webPort, function () {
console.log("Started listening at: " + settings.webPort);
});
Related
This question relates to a Node.js mssql API.
I've recently updated my code to use a SQL.ConnectionPool instead of sql.connect which when combined with an async / await function allowed me to get around connection.close() errors.
In my previous (OLD) executeQuery function, I was able to pass an array which I could push values into to use with "request.input(name, value)"
Function call example:
app.get('/api/route/:id', function (req, res) {
var id = req.params.id;
let x = []
if (id != null && id != NaN) {
x.push({
Name: 'id', Value: id
})
var query = `SELECT * from [Table] where ID = #id`
executeQuery(res, query, arr);
} else {
res.send(500)
}
})
OLD Function:
var executeQuery = function (res, query, arr) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log('Error while connecting to the database: ' + err)
res.send(err)
} else {
// Create the request object
var request = new sql.Request();
if (arr != null) {
if (arr.length > 0) {
for (var obj of arr) {
request.input(obj.Name, obj.Value)
}
}
}
request.query(query, function (err, rs) {
if (err) {
sql.close();
console.log('Error while querying the database : ' + err);
res.send(err);
} else {
sql.close();
console.log(rs)
res.send(rs)
}
})
}
})
}
NEW Function:
var executeQuery = async function(res, query, arr){
const pool = new sql.ConnectionPool(dbConfig);
pool.on('error', err => {
console.log('sql errors ', err);
});
try {
await pool.connect();
let result = await pool.request().query(query);
console.log('success')
res.send(result);
return {success: result};
} catch (err) {
console.log('error')
console.log(err)
res.send(err);
return {err: err};
} finally {
pool.close();
}
}
Question
How do I go about achieving the same request.input process with a ConnectionPool as I did with my previous function ( like the below )
var request = new sql.Request();
if (arr != null) {
if (arr.length > 0) {
for (var obj of arr) {
request.input(obj.Name, obj.Value)
}
}
}
Thank you.
This is my code:
oracledb.getConnection(
{
user : "user",
password : "password",
connectString : "gtmachine:1521/sde1"
},
function(err, connection)
{
if (err) { console.error(err); return; }
connection.execute(
"SELECT filetype, filetypeid from filetype where filetypeid < 6",
function(err, result)
{
if (err) { console.error(err); return; }
response = result.rows;
console.log(response);
res.end(JSON.stringify(response));
});
This is the output
[["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]]
But my front end angularjs is expecting something in this format:
[{"filetype":"Ascii Text","filetypeid":1},{"filetype":"Binary","filetypeid":2}]
Does any one know what is the standard way to convert this?
These will convert your array of arrays into an array of objects:
var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
results = results.map(
function(item) {
return {
filetype: item[0],
filetypeid: item[1]
}
}
);
console.log(results);
And in ES6:
var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
results = results.map(item => ({filetype: item[0], filetypeid: item[1]}));
console.log(results);
I'am using below code to get data from a collection
Marketing.find({
shopId: req.params.shopId,
locationId: req.params.locationId,
}).exec(function (err, campaigns) {
if (err) {
return next(err);
} else if (!campaigns) {
return next(new Error('Failed to load Campaigns '+ req.params.shopId));
}
I want to make a api call on campaigns object i use the below code
campaigns.forEach(function(item) {
async.waterfall([
function (done) {
item.opens = "-";
item.requests = "-";
var currentDate = new Date();
var formatedDate = currentDate.toISOString().slice(0,10);
var request = sg.emptyRequest();
request.queryParams.aggregated_by = 'day';
request.queryParams.limit = '1';
request.queryParams.start_date = '2016-01-01';
request.queryParams.end_date = formatedDate;
request.queryParams.offset = '1';
request.queryParams.categories = item._id;
request.method = 'GET';
request.path = '/v3/categories/stats';
sg.API(request, function (response) {
response.body = JSON.parse(response.body);
done(err,response.body)
});
},
function (data,done) {
for(var i=0;i<data.length;i++){
unique_opens = parseInt(unique_opens)+parseInt(data[i].stats[0].metrics.unique_opens);
opens = parseInt(opens)+parseInt(data[i].stats[0].metrics.opens);
requests = parseInt(requests)+parseInt(data[i].stats[0].metrics.requests);
}
if(unique_opens>=1 && requests>=1){
item.clickrate = (unique_opens/opens)*100;
}
else{
item.clickrate = 0;
}
item.opens = opens;
item.requests = requests;
console.log(item.opens);
opens = 0;
unique_opens = 0;
requests = 0;
console.log(item);
},
], function (error) {
if (error) {
//handle readFile error or processFile error here
}
});
});
And at the end i do
res.json(campaigns);
But it doesn't add the two new keys in each index [ opens & request ]
Use map() as follows:
Marketing.find({
shopId: req.params.shopId,
locationId: req.params.locationId,
}).lean().exec(function (err, campaigns) {
if (err) {
return next(err);
} else if (!campaigns) {
return next(new Error('Failed to load Campaigns '+ req.params.shopId));
}
campaigns = campaigns.map(function(item){
return {
opens: 'SOMELOGIC',
requests: 'SOMELOGIC',
opens: item.opens,
requests: item.requests,
};
});
res.json(campaigns);
}
I can export to Excel with FileSaver in my solution. Here my sources:
tapuController.cs:
[Route("Tapu/tcKimlikNoIleToEcel")]
public void tcKimlikNoIleToEcel(string tcKimlikNo)
{
List<TapuZeminModel> zeminler = new List<TapuZeminModel>();
zeminler = TapuModule.GetZeminListFromTcNo(tcKimlikNo);
List<TapuZeminViewModel> zeminList = new List<TapuZeminViewModel>();
foreach (var zemin in zeminler)
{
foreach (var hisse in zemin.Hisseler)
{
TapuZeminViewModel ze = new TapuZeminViewModel();
ze.Ad = hisse.Kisi.Ad;
ze.AdaNo = zemin.AdaNo;
if (zemin.KatMulkiyeti != null)
{
ze.ArsaPay = zemin.KatMulkiyeti.ArsaPay;
ze.ArsaPayda = zemin.KatMulkiyeti.ArsaPayda;
ze.BagimsizBolumNo = zemin.KatMulkiyeti.BagimsizBolumNo;
ze.Blok = zemin.KatMulkiyeti.Blok;
ze.Giris = zemin.KatMulkiyeti.Giris;
}
ze.Cilt = zemin.CiltNo;
ze.EdinmeSebep = hisse.EdinmeSebep;
ze.HisseId = hisse.TapuKod;
ze.HissePay = hisse.HissePay;
ze.HissePayda = hisse.HissePayda;
ze.Il = zemin.Il.Ad;
ze.Ilce = zemin.Ilce.Ad;
ze.KisiId = hisse.Kisi.TapuKod;
ze.ParselNo = zemin.ParselNo;
ze.Sayfa = zemin.SayfaNo;
ze.Kurum = zemin.Kurum.Ad;
ze.ZeminId = zemin.TapuKod;
ze.ZeminTip = zemin.ZeminTip.Ad;
ze.Mahalle = zemin.Mahalle.Ad;
ze.Nitelik = zemin.AnaTasinmaz.Nitelik;
ze.Mevkii = zemin.AnaTasinmaz.Mevkii;
if (hisse.Kisi.GercekKisi != null)
{
ze.SoyAd = hisse.Kisi.GercekKisi.SoyAd;
ze.TcKimlikNo = hisse.Kisi.GercekKisi.TcKimlikNo;
}
if (hisse.Kisi.TuzelKisi != null)
{
ze.TuzelKisiAd = hisse.Kisi.TuzelKisi.Ad;
ze.VergiNo = hisse.Kisi.TuzelKisi.VergiNo;
ze.SicilNo = hisse.Kisi.TuzelKisi.SicilNo;
}
zeminList.Add(ze);
}
}
StringBuilder dosyaAdi = new StringBuilder();
dosyaAdi.Append(DateTime.Now.ToString("dd.MM.yyyy HH.mm"));
dosyaAdi.Append("-" + tcKimlikNo);
dosyaAdi.Append(".xls");
GridView gv = new GridView();
gv.DataSource = zeminList;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + dosyaAdi.ToString());
Response.ContentType = "application/ms-excel=utf-8";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
tapuControllerService.js:
angular.module('TapuAppModule')
.factory('TapuControllerService', function TapuIlApiFactory($http) {
return {
adaParselSorguToExcel: function (zeminArg) {
return $http({ method: "GET", url: "Tapu/ExportToExcel", params: { ada: zeminArg.Ada, ilceId: zeminArg.IlceId, mahId: zeminArg.MahalleId, parsel: zeminArg.Parsel } });
},
tcKimlikNoIleToEcel: function (manuelTcKimlikNo) {
return $http({ method: "GET", url: "Tapu/tcKimlikNoIleToEcel", params: { tcKimlikNo: manuelTcKimlikNo } });
},
kurumIdIleToEcel: function (manuelKurumId) {
return $http({ method: "GET", url: "Tapu/kurumIdIleToEcel", params: { kurumId: manuelKurumId } });
}
}
});
tapuController.js:
$scope.exportToExcel = function () {
$scope.ZeminArg = {
Ada: $scope.selectedAdaNo,
Parsel: $scope.selectedParselNo,
MahalleId: $scope.selectedMahalle,
IlceId: $scope.selectedIlce
};
if (document.getElementById('adaparsel').className == "tab-pane fade active in") {
var fileName = "MahalleId-" + $scope.ZeminArg.MahalleId + "_IlceId-" + $scope.ZeminArg.IlceId + "_AdaNo-" + $scope.ZeminArg.Ada + "_ParselNo-" + $scope.ZeminArg.Parsel;
TapuControllerService.adaParselSorguToExcel($scope.ZeminArg)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
if (document.getElementById("tckimlikno").className == "tab-pane fade active in") {
var fileName = "TcNo-" + $scope.manuelTcKimlikNo;
TapuControllerService.tcKimlikNoIleToEcel($scope.manuelTcKimlikNo)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
if (document.getElementById("kurum").className == "tab-pane fade active in") {
var fileName = "kurum-" + $scope.manuelKurumId;
TapuControllerService.kurumIdIleToEcel($scope.manuelKurumId)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
};
And i'm using FileSaver. Here filesaver Url
Everything is ok. It's working. But i can't use Turkish chars. I tried some encoding but not worked. Here is my error's pic:
For example first SoyAd is : FERİKOĞLU
Second row Ad is : ALATTİN
etc. What should i do for output Excel with Turkish Chars??
I'm currently starting work for my bachelor thesis and recently started 'digging' into the use of node.js and webSocket. My webSocket server runs without problems when accessed in Firefox 15.0 and Chrome 21.0.1180.89 m. In Opera 12.02, there seems to be a problem with the client-server handshake. This is what Opera's error console says:
[31.08.2012 01:03:51] WebSockets - http://10.0.0.2/
Connection
WebSocket handshake failure, invalid response code '400'.
Funny thgough: I can't find this error anywhere in the Dragonfly console's network log. All the fields that are requested when accessing the website (index.html, client.js etc.) are found and served as they should be (HTTP Status code 200 OK). Also, the only status codes that my server returns are 200, 404 and 500, so this looks like it's coming from within webSocket itself.
And yes, webSocket IS enabled in Opera...I have no idea what the problem could be
Any help would be really appreciated :)
EDIT:
This is my code so far so you can see which headers my server sends and how I create webSocket connections with my client.js:
server.js:
// load required modules:
var http = require("http");
var WebSocketServer = require("websocket").server;
path = require("path");
url = require("url");
filesys = require("fs");
// declare listening port vars:
var httpListeningPort = 80;
var webSocketListeningPort = 80;
// create HTTP-server:
var httpSrv = http.createServer(function(request, response) {
console.log((new Date()) + ":\tReceived request for " + request.url);
// response.writeHead(200);
// response.end();
var myPath = url.parse(request.url).pathname;
var fullPath = path.join(process.cwd(), myPath);
if(myPath === "/") {
fullPath += "index.html";
console.log("Full path:\t" + fullPath);
filesys.readFile(fullPath, "binary", function(err, file) {
if(err) {
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
}
else {
response.writeHeader(200);
response.write(file, "binary");
response.end();
}
});
}
else {
path.exists(fullPath, function(exists) {
if(!exists) {
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else {
filesys.readFile(fullPath, "binary", function(err, file) {
if(err) {
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
}
else {
response.writeHeader(200);
response.write(file, "binary");
response.end();
}
});
}
});
}
});
httpSrv.listen(httpListeningPort, function() {
console.log((new Date()) + ":\tServer is now listening on port " + httpListeningPort);
});
// create webSocket server and tie it to the http server:
wsServer = new WebSocketServer({
httpServer: httpSrv
});
function originChecker(origin) {
if(origin) {
console.log("Origin " + origin + " is allowed");
return true;
} else {
console.log("origin is NOT allowed.");
return false;
}
}
// how to handle requests:
wsServer.on("request", function(request) {
// check whether origin is allowed or not:
if(originChecker(request.origin) === false) {
request.reject();
console.log((new Date()) + ":\tConnection request from origin " + request.origin + " rejected.");
return;
}
// accept the connecteion request -> open the connection:
var connection = request.accept(null, request.origin);
console.log((new Date()) + ":\tConnection request from " + request.origin + " accepted.");
// handle incoming messages from the clients:
connection.on("message", function(message) {
if(message.type === "utf8") {
console.log((new Date()) + ":\tReceived message from " + request.origin + ":\nType: " + message.type + "\nLength: " + message.utf8Data.length + "\nMessage: " + message.utf8Data);
// echo "Message received":
connection.sendUTF(JSON.stringify( { type: "message", data: "Message received !" } ));
} else {
// send error message back to client:
console.log((new Date()) + ":\tReceived message from " + request.origin + ":\nERROR:\tMessage is NOT UTF-8! it's " + message.type);
connection.sendUTF(JSON.stringify( { type: "message", data: "ONLY UTF-8 accepted !" } ));
}
});
// what to do when connection is closed:
connection.on("close", function() {
console.log((new Date()) + ":\tClient #" + connection.remoteAddress + " disconnected.");
});
});
client.js:
function client() {
if("WebSocket" in window) {
alert("WebSocket is supported by your browser!");
// try to connect to the webSocket server:
var connection = null;
connection = new WebSocket("ws://10.0.0.2:80");
// things to do once the connection is opened:
connection.onopen = function() {
alert("INFO:\tConnection to server is OPEN");
document.getElementById("msgInput").focus();
document.getElementById("msgInput").disabled = false;
document.getElementById("msgInput").value = "";
document.getElementById("msgInput").onkeyup = function(key) {
switch(key.keyCode) {
case 13: if(document.getElementById("msgInput").value === "") {
break;
}
var messageText = document.getElementById("msgInput").value;
document.getElementById("msgInput").disabled = true;
document.getElementById("msgInput").value = "";
document.getElementById("statusHeader").innerHTML = "Sending...";
connection.send(messageText);
break;
default: document.getElementById("statusHeader").innerHTML = "Press ENTER to send!";
}
};
};
connection.onerror = function(error) {
document.body.style.backgroundColor = "#220000";
document.body.style.color = "#aa0000";
document.getElementById("statusHeader").innerHTML = "ERROR connecting to server -> OFFLINE";
return;
};
connection.onmessage = function(message) {
try {
var json = JSON.parse(message.data);
} catch (error) {
alert("ERROR parsing message:\t" + error);
return;
}
document.getElementById("statusHeader").innerHTML = json.data;
document.getElementById("msgInput").disabled = false;
};
connection.onclose = function() {
setTimeout(function() {
document.body.style.backgroundColor = "#808080";
document.body.style.color = "#ffffff";
document.getElementById("statusHeader").innerHTML = "OFFLINE";
document.getElementById("msgInput").disabled = true;
document.getElementById("msgInput").value = "OFFLINE";
}, 5000);
return;
};
} else {
alert("WebSocket is NOT supported by your browser! Exiting now.");
return;
}
};
According to a recent question Opera 12 supports an older, incompatible version of websockets. This version (Hixie-76) uses a different set of headers in its handshake. Your server presumably doesn't understand these which explains its 400 error response.
If you can afford to wait for Opera to catch up, the easiest 'solution' is to use other browsers for your testing for now. The hixie protocol drafts are deprecated so Opera is bound to upgrade to RFC 6455 eventually.