Why can't my Nodejs application cannot see my sqlite3 database column? - html

There are not errors associated with database or table, but it is not seeing the columns. This is the error:
Node server is running..
SQLITE_ERROR: no such column: scene
This is the table:
CREATE TABLE animalStream (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cascade_name TEXT NOT NULL,
enclosre_name TEXT NOT NULL,
scene TEXT NOT NULL,
sensorCamAddress TEXT NOT NULL,
streamerCamAddress TEXT NOT NULL,
duration INTEGER NOT NULL
);
The Nodejs code below allows me to receive data from the HTML form
const path=require('path');
const sqlite3 = require("sqlite3").verbose();
const db_name = path.join(__dirname, "wildlife.db");
const db = new sqlite3.Database(db_name);
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendFile('/home/harry/interface/in9.html');
});
app.post('/submit-student-data', function (req, res) {
var scene = req.body.scene
var cascade_name = req.body.cascade_name;
var enclosre_name = req.body.enclosre_name;
var sensorCamAddress = req.body.sensorCamAddress
var streamerCamAddress = req.body.streamerCamAddress
var duration = req.body.duration;
db.run(`INSERT INTO animalStream(scene) VALUES(scene)`, ['C'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
});/////////////////
var server = app.listen(3000, function () {
console.log('Node server is running..');
});
<!DOCTYPE html>
<html><body style="background-color:black;"><blockquote><blockquote>
<form action="/submit-student-data" method="post">
<p style="color:white;">Cascade file name:<br>
<input type = "text" name = "cascade_name" /></p>
<p style="color:white;">Enclosure name:<br>
<input type = "text" name = "enclosre_name" /></p>
<p style="color:white;">Scene number:<br>
<input type = "text" name = "scene" /></p>
<p style="color:white;">Sensor Camera IP address:
<br> <input type = "text" name = "sensorCamAddress" /></p>
>
<p style="color:white;">Streamer Camera IP address:
<br> <input type = "text" name = "streamerCamAddress" /></p>
<p style="color:white;">Scene duration:
<br><input type = "text" name = "duration" /></p>
<br>
<center> <INPUT type="submit" value="Send"> <INPUT type="reset"></center>
</form>
</blockquote></blockquote>
</body></html>
As I mentioned, it seems to pick up the database and table fine. It just doesn't see the columns for some reason. I would appreciate any input.

I think you must write your query like this:
`INSERT INTO animalStream (scene) VALUES("${scene}")`
and also you didn't set any value to other column that set NOT NULL

Related

How to display var from javascript to html?

I keep getting an error for the last line in generatePassword()," document.getElementById(output).innerHTML = outHash;" Any ideas on how to display this variable?
<html>
<body>
<p>Enter your text here </p>
<input type="text" value="Enter password here" id="userInput">
<button onclick="generatePassword()">Generate</button>
<p>Hash output <span id="output"></span></p>
<script>
function generatePassword() {
var Input = document.getElementById("userInput");
var outHash = digestMessage(Input);
var displayHash = [];
document.getElementById(output).innerHTML = outHash;
}
async function digestMessage(message) {
var encoder = new TextEncoder();
var data = encoder.encode(message);
var hash = await crypto.subtle.digest('SHA-256', data);
return hash;
}
</script>
</body>
Change output in document.getElementById(output) to a string ("output") and it should work. Your javascript is trying to call a variable that doesn't exist.

Deleting trigger auto-deleted my script project

When I deleted my only trigger (set to run daily) it took all of my script code with it!
When I now go into Tools/Script Editor it shows a blank project (not the saved code I've been working on for a month!)
Restoring previous versions of the spreadsheet doesn't work and I am using the account that I created it in.
I don't know where Sheets automatically stores the .gs files (they don't show on my Drive) but I'm hoping it still exists on their servers and it's just the link to it from the spreadsheet got broken and can be restored.
Please help as I do not want to start from scratch again 🙏
Here is a script that I use for backing up my files as both separate files and one big JSON file. It won't help you fix your current problem but you can use to avoid it in the future and unlike backing up the entire spreadsheet and creating another unnecessary project, they get saved as ascii text files.
function saveScriptBackupsDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('backupscripts1'), 'Script Files Backup Dialog');
}
function scriptFilesBackup(obj) {
console.log(JSON.stringify(obj));
const scriptId = obj.script.trim();
const folderId = obj.folder.trim();
const saveJson = obj.saveJson;
const saveFiles = obj.saveFiles;
const fA = obj.selected;
if (scriptId && folderId) {
const base = "https://script.googleapis.com/v1/projects/"
const url1 = base + scriptId + "/content";
const url2 = base + scriptId;
const options = { "method": "get", "muteHttpExceptions": true, "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
const res1 = UrlFetchApp.fetch(url1, options);
const data1 = JSON.parse(res1.getContentText());
const files = data1.files;
const folder = DriveApp.getFolderById(folderId);
const res2 = UrlFetchApp.fetch(url2, options);
const data2 = JSON.parse(res2.getContentText());
let dts = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyyMMdd-HH:mm:ss");
let subFolderName = Utilities.formatString('%s-%s', data2.title, dts);
let subFolder = folder.createFolder(subFolderName);
if (saveFiles) {
files.forEach(file => {
if (file.source && file.name) {
let ext = (file.type == "HTML") ? ".html" : ".gs";
if (~fA.indexOf(file.name)) {
subFolder.createFile(file.name + ext, file.source, MimeType.PLAIN_TEXT)
}
}
});
}
if (saveJson) {
subFolder.createFile(subFolderName + '_JSON', res1, MimeType.PLAIN_TEXT)
}
}
return { "message": "Process Complete" };
}
The html for the dialog:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
input {margin: 2px 5px 2px 0;}
#btn3,#btn4{display:none}
</style>
</head>
<body>
<form>
<input type="text" id="scr" name="script" size="60" placeholder="Enter Apps Script Id" onchange="getFileNames();" />
<br /><input type="text" id="fldr" name="folder" size="60" placeholder="Enter Backup Folder Id" />
<div id="shts"></div>
<br /><input type="button" value="0" onClick="unCheckAll();" size="15" id="btn3" />
<input type="button" value="1" onClick="checkAll();"size="15" id="btn4"/>
<br /><input type="checkbox" id="files" name="saveFiles" checked /><label for="files">Save Files</label>
<br /><input type="checkbox" id="json" name="saveJson" checked /><label for="json">Save JSON</label>
<br /><input type="button" value="Submit" onClick="backupFiles();" />
</form>
<script>
function getFileNames() {
const scriptid = document.getElementById("scr").value;
google.script.run
.withSuccessHandler((names) => {
document.getElementById('btn3').style.display = "inline";
document.getElementById('btn4').style.display = "inline";
names.forEach((name,i) => {
let br = document.createElement("br");
let cb = document.createElement("input");
cb.type = "checkbox";
cb.id = `cb${i}`;
cb.name = `cb${i}`;
cb.className = "cbx";
cb.value = `${name}`;
cb.checked = true;
let lbl = document.createElement("label");
lbl.htmlFor = `cb${i}`;
lbl.appendChild(document.createTextNode(`${name}`));
document.getElementById("shts").appendChild(cb);
document.getElementById("shts").appendChild(lbl);
document.getElementById("shts").appendChild(br);
});
})
.getAllFileNames({scriptId:scriptid});
}
function unCheckAll() {
let btns = document.getElementsByClassName("cbx");
console.log(btns.length);
for(let i =0;i<btns.length;i++) {
btns[i].checked = false;
}
}
function checkAll() {
let btns = document.getElementsByClassName("cbx");
console.log(btns.length)
for(let i = 0;i<btns.length;i++) {
btns[i].checked = true;
}
}
function backupFiles() {
console.log('backupFiles');
sObj = {};
sObj.script = document.getElementById('scr').value;
sObj.folder = document.getElementById('fldr').value;
sObj.saveJson = document.getElementById('json').checked?'on':'';
sObj.saveFiles = document.getElementById('files').checked?'on':'';
sObj.selected = [];
console.log("1");
const cbs = document.getElementsByClassName("cbx");
let selected = [];
for(let i = 0;i<cbs.length; i++) {
let cb = cbs[i];
if(cb.checked) {
sObj.selected.push(cb.value)
}
}
console.log("2");
google.script.run
.withSuccessHandler(function(obj){google.script.host.close();})
.scriptFilesBackup(sObj);
console.log(JSON.stringify(sObj));
}
</script>
</body>
</html>
If you want the restore just ask. I haven't used it that much I usually the file that I need and paste past it in.

Posting fetched data in database

I am trying to fetch user info through a form and then insert same data in the table 'orders'.
Everything looks correct, but there is an error showing total_cost is undefined.
I tried declaring it globally as well.
total_cost should be the quantity selected by the user in the form multiplied by the price of the product which is fetched from the database.
Here is the app.js post request:
// post create_order page
app.post("/create_order", function(req, res){
var name = req.body.name;
var quantity = req.body.quantity;
var email = req.body.email;
// fetching price from menu table
var sql = "select Price from menu where Name=?";
db.query(sql,[name], function(err, result){
if(err){
throw err;
}else if(result==0){
console.log("No items found!!!")
}else{
console.log(result)
console.log(Price)
var total_cost = result;
console.log(total_cost )
}
})
// Updating the order table
let today = new Date().toISOString().slice(0, 10);
let order = {
Item : name,
Quantity : quantity,
TotalCost : total_cost,
Date : today,
email : user
}
sql1 = "Insert into orders SET ?";
db.query(sql1, order, function(err, result2){
if(err){
throw err;
}else{
res.redirect("/orders");
}
})
})
Here is the corresponding order form used to fetch data:
<!-- //Order form goes here -->
<div class="orderform">
<form action="/create_order" method="POST">
<div class="form-group">
<label for="exampleFormControlSelect1">Select Item</label>
<select class="form-control" name="name" id="exampleFormControlSelect1">
<%result.forEach(function(result){%>
<option><%=result.Name%></option>
<%})%>
</select>
</div>
<div class="form-group" >
<label for="exampleFormControlInput1">quantity</label>
<input type="number" name="quantity" class="form-control" id="exampleFormControlInput1" placeholder="quantity" min="1" max="10">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleFormControlInput1" placeholder="name#example.com">
</div>
Screenshot of error page:
Error page I am getting upon submitting the form
You defined your variable inner-scope; this will cause issues!
let profile = 20;
function call() {
console.log(profile); // == 20
let profile2 = 26;
}
call();
console.log(profile2); // undefined in other words your error.
If it's not a scope issue, then it's certainly the data you're grabbing from data-base is incorrect. Double check the query.

Can't login into a site using Google Apps Script and receive error 422

I need to scrape private data from a Japanese site.
But I can't login into the site and receive error code 422.
How can I login?
I need to log in into this website:
https://moneyforward.com/users/sign_in
The form on this site is:
<form class="form-horizontal mf-mb40" id="new_sign_in_session_service" action="/session" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="authenticity_token" value="OGuijdFq6M1xngenCHi0BgZh9x0Nniw2HxiRhC9H2T0vbgWcWNRz+fmi5wxEdk4ua5TL9/UF7BapR2Af8CdILQ==" />
<div class="a-text--f14 mb3">e-mail</div><div class="a-text-box">
<input placeholder="entry" class="js-focus-form" type="email" name="sign_in_session_service[email]" id="sign_in_session_service_email" />
</div>
<div class="a-text--f14 mb3 mt20">password</div><div class="a-text-box">
<input placeholder="entry" type="password" name="sign_in_session_service[password]" id="sign_in_session_service_password" />
</div>
<div class="m-password-support">
<div class="a-checkbox password-show">
<label><input class="checkbox" id="show-ps" name="new1" type="checkbox" value="1" />
<span class="checkbox-icon"></span>
<span class="checkbox-txt">password</span></label>
</div>
<div class="password-forget">
forgot password
</div>
</div>
<div class="a-button primary">
<input type="submit" name="commit" value="login" id="login-btn-sumit" data-disable-with="login" />
</div>
</form>
I receive the error on last row "var response = UrlFetchApp.fetch(url, options)" below code.
function Login() {
var account ='***';
var password = '***';
var response = UrlFetchApp.fetch("https://moneyforward.com/users/sign_in");
var regexp = /<input type=\"hidden\" name=\"authenticity_token\" value=\"(.*?)\" \/>/;
var elements = response.getContentText().match(regexp);
var headers = response.getAllHeaders();
var cookies = [];
if ( typeof headers['Set-Cookie'] !== 'undefined' ) {
var cookies = typeof headers['Set-Cookie'] == 'string' ? [ headers['Set-Cookie'] ] : headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
};
var payload = {
utf8: "✓",
authenticity_token : elements[1],
email : "account",
password : password
};
var headers = { 'Cookie' : cookies };
options = {
method : "post",
headers : headers,
followRedirects: true,
contentType: "application/x-www-form-urlencoded",
//muteHttpExceptions : true,
payload : payload,
};
var url = "https://moneyforward.com/session";
var response = UrlFetchApp.fetch(url, options);
}

Issue Inserting MySQL Record With Node.js and Handlebars

I am having an issue when trying to submit a form with user information that inserts into a table. I have a userForm that allows user data to be entered with the following:
<form id="userForm">
<fieldset>
<legend>Add User</legend>
<p>First Name: <input id="fname" type="text" name="fname"/></p>
<p>Last Name: <input id="lname" type="text" name="lname"/></p>
<p>Email: <input id="email" type="text" name="email"/></p>
<p>Password: <input id="password" type="text" name="password"/></p>
</fieldset>
<input id="addUser" type="submit" name="add" value="Add User" onclick="addRow()" />
</form>
<script src="script.js"></script>
This then launches the following code in my script.js code:
function addRow(){
var form = document.getElementById("userForm");
var req = new XMLHttpRequest();
// Add the form data to the ajax request
var queryString = "";
var fname = form.fname.value;
var lname = form.lname.value;
var email = form.email.value;
var password = form.password.value;
queryString += "fname=" + fname + "&";
queryString += "lname=" + lname + "&";
queryString += "email=" + email + "&";
queryString += "password=" + password;
req.open('GET', '/insert-user?' + queryString, true);
req.send();
console.log(req.status);
Which executes the server side code:
app.get('/add-user', function(req,res){
var context = {};
res.render('addUser', context);
});
app.get('/insert-user',function(req,res,next){
var context = {};
pool.query("INSERT INTO user (`fname`, `lname`, `email`, `password`) VALUES (?,?,?,?)",
[req.query.fname, req.query.lname, req.query.email, req.query.password],
function(err, result){
if(err){
next(err);
return;
}
context.results = "Inserted id " + result.insertId;
res.render('exerciseTable',context);
});
});
The record is not being inserted into the table. When I console.log(req.status) I see 0 in the console. The add-user page is the form that the user fills out and then the insert-user code is called but it does not seem to be working. In fact, the URL does not change from http://18.219.103.143:3000/add-user to http://18.219.103.143:3000/insert-user? when I submit. It just stays static. It seems like my app.get('/insert-user'... code isn't even being called. Does anyone know what I am missing?
I am getting this error in the console:
Try to put
<form id="userForm" onsubmit="return false;">
Otherwise the default action on your form will be called. As your button is a submit button and that your default action is not set so it defaults to the same page and returning nothing or true will reload your page.