Node.js translator - javascript

I am trying to create a back end for my front-end web page using Node.JS. The web page is using google translate API and translates the users word. At the moment I am able to get it to work when I hard code the word and the language to/from. What i am trying to do is retrieve the word they input and the language they want to translate to.
Code from front end
function translateWord() {
var url = 'http://localhost:8085';
var endpoint = '/translate';
var fromLang = document.getElementById("fromLang").value;
var toLang = document.getElementById("toLang").value;
var word = document.getElementById("wordInput").value;
var payload = {"word": word, "from": fromLang, "to": toLang};
console.log(payload);
var http = new XMLHttpRequest();
http.open("POST", url+endpoint, true);
http.setRequestHeader("Content-type", "application/json");
http.onreadystatechange = function() {
var DONE = 4; // 4 means the request is done.
var OK = 200; // 200 means a successful return.
if (http.readyState == DONE && http.status == OK && http.responseText) {
var reply = http.responseText;
document.getElementById("mainBody").innerHTML = reply;
}
};
var params = JSON.stringify(payload);
// Send request
http.send(params);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Translation Demo</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
</head>
<body>
<script src="js/main.js"></script>
<div>
<h1> Translation Demo </h1>
<p>Word:<input id="wordInput" type="text"></p>
<p>From:
<select id="fromLang">
<option value="en" selected>English</option>
<option value="fr">French</option>
<option value="es">Spanish</option>
<option value="ru">Russian</option>
</select>
To:
<select id="toLang">
<option value="en">English</option>
<option value="fr" selected>French</option>
<option value="es">Spanish</option>
<option value="ru">Russian</option>
</select>
</p>
<button onclick="translateWord()">Translate</button>
<p id="mainBody">Translation here.</p>
</div>
</body>
</html>
This is the back end I am having trouble with (this part works because its hard coded).
var express = require('express');
var router = express.Router();
var cors= require('cors');
router.use(cors());
router.post('/translate', function(req, res)
{
var payload = req.body;
var word = "hello";
var json = { from: 'en', to: 'fr' };
const translate = require('google-translate-api');
translate(word, json).then(function (resolve, reject){res.send(resolve.text.toString());});
});
module.exports = router;
To be able to grab the word and language, I tried doing something along the lines of this. Also I have it going to port 8085 so that's not the problem.
var payload = req.body;
var word = req[word];
var from = req[from];
var to = req[to];
var json = { from: 'from', to: 'to' };
When i try doing it this way i receive this error.
(node:6892) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'length' of undefined
Could someone point me in the right direction as to what I am doing wrong? I have been trying to solve this for awhile and haven't been able to.

By default, ExpressJS won't be able to parse JSON post data. To solve this, you can use the body-parser module.
Install it:
npm i -S body-parser
And use it like so in your code:
var express = require('express');
var bodyParser = require('body-parser'); // <----------------------------
var jsonParser = bodyParser.json(); // <----------------------------
var router = express.Router();
var cors= require('cors');
router.use(cors());
router.post('/translate', jsonParser, function (req, res) // <-----------
{
/* ... */
});
module.exports = router;
Then, inside that function, you'll be able to access your data:
var word = req.body.word;
var json = {
from: req.body.from,
to: req.body.to
};

Related

Nodejs is not fully functional when running on autostart

I am currently trying to change the volume of my Raspberry Pi with two html buttons (volume up and volume down), using nodeJS. The volume change is done by calling a bash script when clicking on one of the html-buttons in index.html.
When I start node manually from terminal with
node server.js
everything works fine and I can increase and decrease the volume using the two buttons.
As soon as I put the node script to autostart, only the "volume up" button is working, while the volume down does not seem to be working.
Killing the autostarted node process and starting it manually, it works just fine again.
How can the outcome be this different, depending on how node is started here?
What is my error in this?
My node script looks like this:
var express = require('express');
var path = require('path');
var open = require('open');
var fs = require('fs');
const { exec } = require('child_process');
var bodyParser = require('body-parser');
var port = 3000;
var app = express();
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(request, respond) {
var inputValue = request.body.volume;
if (inputValue == "up") {
exec('sh volumeup.sh');
}
if(inputValue == "down") {
exec('sh volumedown.sh');
}
});
app.listen(port, function(err){
if(err){
console.log(err);
}else{
open('http://localhost:' + port);
}
});
with my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h2>Change Volume</h2>
<form action="" method="post">
<button name="volume" value="up">Volume Up</button>
<button name="volume" value="down">Volume Down</button>
</form>
</body>
</html>
To get the nodejs to run on autostart, I have set up a *.desktop-file:
[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=<Node>
Comment=
Exec=/usr/bin/node /home/pi/Desktop/server.js
StartupNotify=false
Terminal=true
Hidden=false
Thank you very much in advance, I really appreciate your help!
Figured it out by myself.
In case anyone is facing a similar issue:
What helped me, was to put both shell file names into their absolute path:
´´´
app.post('/', function(request, respond) {
var inputValue = request.body.volume;
if (inputValue == "up") {
exec('sh /home/pi/server/volumeup.sh');
}
if(inputValue == "down") {
exec('sh /home/pi/server/volumedown.sh');
}
});
´´´
Bothered me for longer than I want to admit :-)

Not able to cross beyond my sql statement , the browser waits for something

I am new to node js and js, My code is not able to cross the SQL statement
here is my app.js snippet for the SQL statement
my app.js
//declaration
const bodyParser = require("body-parser")
const fs = require('fs')
const express = require('express')
const app = express()
var session = require('express-session');
const path = require('path')
app.use("/static", express.static('./static/'));
//For the body parser
app.use(bodyParser.urlencoded({extended: false}))
//parse the application Json
app.use(bodyParser.json())
// for the MySQL page
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'login'
})
app.get ('/todo',(req,res)=>{
res.writeHead(200,{'content-type' : 'text/html'})
fs.createReadStream('project1.html').pipe(res)
})
app.listen(process.env.PORT || 3000)
my todo.js
document.addEventListener('submit',myFunction)
function myFunction(e){
console.log("in the data post method")
let sql = 'INSERT INTO `acc` (`name`) VALUES (?)'
connection.query(sql,req.body.name,(error,result)=>{
if(error) throw error
console.log('value inserted')
connection.end();
})
e.preventDefault();
var text = document.querySelector("input").value;
var text = document.querySelector("input").value;
var node = document.createElement("p");
node.id="li1"
if (text!=""){
var textnode=document.createTextNode(text);
node.appendChild(textnode); //append the value to LI
text = document.getElementById("demo")
console.log(text) ;
document.getElementById("demo").appendChild(node); //append the value to UI
document.querySelector("input").value = ""
}
// document.getElementById("demo").addEventListener('mouseover',myFunction1)
str = document.getElementById("li1")
console.log(str)
}
//SELECTING AN ELEMENT THAT WAS CREATAED DYNAMICALLY AND APPLLY SOME PROPERTY
$(document).on('click','p',function(){
$(this).css({"text-decoration": "line-through",color : "pink" });
$(this).fadeOut(1500);
// $(this).remove();
})
my project1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create a table</title>
<script src="./static/todo.js"></script>
</head>
<body>
<h1>ToDo</h1>
<form id="form" action="/data" method="post">
<input type="text" name = "name" class="input" id="tt">
</form>
<div id= "lip">
<ul id="demo" id="demo">
</ul>
</div>
</body>
</html>
I want to insert the user typed value in the database as well as I have to list them in the front end, both codes work separately but when I combine them, after executing the SQL statement the browser waits for something
Please help me.

How can I make an HTML page that edits variables in a .JSON file?

Basically I have a .json file, and I want to make a html page that someone can fill out a form, and the information in the form will change variables in the JSON file.
Example:
The json file (for example):
{“title”: “(variable)”}
then when the html form is submitted it will read (variable) as what was entered into the form.
It depends on what you have on the backend (Node, python, etc)
Welcome to Stackoverflow, seeing that you have NodeJS, you may want to establish some sort of communication from your back end to front end. Let's say you're using websockets. Here is how information would be passed:
userData.json:
{
name: "Mishra",
age: 89
}
server.js:
const app = express()
const server = app.listen(3000) // setup express server
const io = require('socket.io').listen(server); // using websockets
let userData = require('./userData.json');
// on socket connection event
io.on('connection', (socket) => {
socket.on('updateName', name => { // when updateName is called
userData.name = name // set JSON var to new name
})
}
// method to save JSON file goes here
myForm.html:
<head>
<script type="text/javascript" src="your/path/to/socket.io.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
Set name:
<input type="text" id="nameField" name="fname"><br>
<input type="submit" value="Submit" id="submit">
<script>
document.getElementById("submit").onclick = () =>{
socket.emit("updateName", document.getElementById("nameField").value)
}
</script>
</body>

Submit value from HTML form to Node-js

I want to submit input value from HTML form to Node-js. Node-js should assign that value as an argument to a Solidity function. But the Error: TypeError: Cannot read property 'oinput' of undefined is shown. What should i do? Please help a beginner.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Alireza</title>
<body>
<form id="FORM" name="FORM" method="POST" action="http://127.0.0.1:1408">
<input id="Finput" name="oinput" value="Null" onclick="this.form.submit()"/>
</form>
<script>
document.forms[0].oinput.value=prompt("Type a thing: ","Here ...");
</script>
</body>
</html>
app.js:
var express=require('express');
var app=express();
var fs=require('fs');
var http = require('http');
var bodyParser=require('body-parser');
var Web3=require('web3');
var web3=new Web3('ws://127.0.0.1:8545');
var YerevanJSON="E:/Alireza/build/contracts/Yerevan.json";
var YerevanJS=JSON.parse(fs.readFileSync(YerevanJSON));
var YerevanABI=YerevanJS.abi;
var Yerevan=new web3.eth.Contract(YerevanABI, "0x1E6B6524e7da86bafa5ac948b38dA68e6841f0c7");
Yerevan.defaultAccount="0x152AfF6BBF98F2FF2EFAdA32E2ba85CC231cbA13";
app.post("/", function(q,r){
Yerevan.methods.eval(q.body.oinput).send({from:"0x33aa0ba26Dc247BA5d94545344c413949B746360"});
});
app.listen(1408, err=>{ console.log('ERROR')});
Solidity:
pragma solidity ^0.5.12;
contract Yerevan{
string public city;
function eval(string memory sense) public returns(string memory){
city=sense;
return city;
}
}
You have included body-parser on to the file but hasn't asked the app use it.
add below line
const bodyParser = require("body-parser");
// for parsing application/json
app.use(bodyParser.json());
//for parsing application/xwww-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
You are using var, start using const and let instead.

Attempting to insert into mongodb through javascript and html

I'm fairly new to mongodb, node and the like, I was trying to perform a simple task of inserting a blogpost into my database that I already created, what I decided to do is to make a web page with a button, once clicked, would then insert into my mongo database, but unfortunately I've been failing to do so. I know to insert I must use the terminal, for example node server.js and then it'll insert, however I want that to occur by just pressing the button on the html page. So any advice on what to do will be appreciated, the following is my current code.
<!DOCTYPE html>
<html>
<head>
Add Blog Post
</head>
<body>
<h1>
Welcome to your Blog! Feel free to add a blog post!
</h1>
<form>
Title: <br>
<input type = "text" name = "Title" id = "title"><br>
Blog Post: <br>
<input type = "text" name ="EnterBlog" id = "blog"> <br>
<input type = "button" value = "Submit Blog" onclick="
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('blog');
var title = Title.value;
var blog = EnterBlog.value;
// Insert some documents
collection.insertMany([
{Title: title}, {Blog : blog}
], function(err, result) {
assert.equal(err, null);
assert.equal(2, result.result.n);
assert.equal(2, result.ops.length);
console.log('Inserted 2 documents into the Blog collection');
callback(result);
});
}
exports.insertDocuments = insertDocuments;
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/blogapp';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log('Connected correctly to server');
insertDocuments(db, function() {
db.close();
});
});"
>
</form>
</body>
</html>

Categories