I'm fetching application details from the play store using the application package name.
The information that i want to print is not getting printed on the web page and html as well.
the node js code (server .js) is
var http = require('http');
var fs = require('fs');
var formidable = require("formidable");
var util = require('util');
var googlePlaySearch = require('google-play-search');
var appName = " ";
var gameData = " ";
var server = http.createServer(function (req, res) {
if (req.method.toLowerCase() == 'get') {
displayForm(res);
} else if (req.method.toLowerCase() == 'post') {
processAllFieldsOfTheForm(req, res);
}
});
function displayForm(res) {
fs.readFile('form.html', function (err, data) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': data.length
});
res.write(data);
res.end();
});
}
function processAllFieldsOfTheForm(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
//Store the data from the fields in your data store.
//The data store could be a file or database or any other store based
//on your application.
res.writeHead(200, {
'content-type': 'text/plain'
});
var url = fields;
googlePlaySearch.fetch(url, function (err, gameData) {
console.log(gameData);
appName = gameData;
res.write('received the data:\n\n');
res.end(util.inspect({
fields: appName,
})); //for end
}); //for parse
});
}
server.listen(1185);
console.log("server listening on 1185");`enter code here`
and the html code is(form.html) :
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="PACKAGE NAME" />
<br />
<label for="email">Email:</label>
<input type="submit" value="SUBMIT" />
</fieldset>
</form>
</body>
</html>
Please help me with the code.
Thank you.
Related
I am trying to make a basic login system using Express, where if the user's username and password are correct according to a MySQL database, it adds a short "Success!" or "Failure" message to the bottom of the page when it receives a POST request.
I've tried using res.write("<p>Success!</p>") and res.send("<p>Success!</p>"), but neither have worked - instead they just create a new page with "Success!".
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="contact-form" method="POST" action="/login">
<label for="Username">Username: </label>
<input name="Username" maxlength="45"><br><br>
<label for="Password">Password: </label>
<input name="Password" type="password" maxlength="45"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
JS:
const port = 3000;
const express = require("express");
const mysql = require("mysql2");
const app = express();
const bodyParser = require("body-parser");
var conn = mysql.createConnection({
host: "localhost",
database: "database",
user: "<Username>",
password: "<Password>"
});
conn.connect((err) => {
if(err) throw err;
console.log("Connected to database.");
})
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({
extended: false
}));
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/Login.html");
});
app.post("/login", (req,res) => {
let form = req.body;
let sqlQuery = "SELECT * FROM logins WHERE Username = '" + form.Username + "' AND Password = '" + form.Password + "';";
conn.query(sqlQuery, (err, result, fields) => {
if(err) throw err;
if(result.length == 1) {
res.write("<p>Success!</p>")
} else {
res.write("<p>Failure.</p>")
}
})
});
app.listen(port);
So, how could I append a short p element / text to the bottom of an HTML file?
Okay,
So when the submit button in the login form is hit, it creates a totally new request and the old page is no longer in the context of request.
So, res.write() creates a new page, since a new request is generated.
If you want to append the failure and success messages on the same page, you can use ajax request instead of default form submission.
Send the ajax request, you will receive the response without a page reload, and then upon receiving the response, using javascript, you can append a new element with message from the server
const contactForm = document.getElementById('contact-form');
contactForm.addEventListener('submit',(e)=>{
e.preventDefault();
const username = contactForm.elements['username'].value;
const password = contactForm.elements['password'].value;
// now make the ajax call, you can use any library like FetchAPI, axios or even jQuery Ajax
fetch('http://backend/endpoint',{
method: 'POST',
body: JSON.stringify({username,password})
})
.then((res)=>{
return res.json();
})
.then((data)=>{
console.log(data)
// you can append new element here
// based on data (success or failure)
})
})
I have an error when I send data from client side (angular.js) to server side (node.js).
I created a form that the user insert data then my controller get the data and sent it to the server to save the data in mongoose and s3(amazon).
I must say that it works fine - I mean I can save all the information I need, I can see it in my DB and I can see the image on s3
but, I get an error : POST http://localhost:3000/upload 500 (Internal Server Error)
my html form:
<html ng-app="mymed">
<head>
<title>insert</title>
</head>
<body ng-controller="tryController">
<main>
<body>
<form class="form-group" enctype="multipart/form-data" method="POST" action="http://localhost:3000/upload">
<label for="inputEmail3" class="col-sm-2 control-label">Title:</label>
<input class="form-control" type="text" placeholder="Title" ng-model="Title" name="Title" required></input>
</div>
<div class="col-sm-10">
<br>
<input type="file" name="file" accept="image/*" ng-modle="file"></input>
</div>
</div>
<input type="submit" class="btn btn-default" name="send" ng-click="createInsert()"></input>
</form>
.....
<script src="js/appController.js"></script>
my controller:
mymedical.controller('tryController',['$scope','$http','$cookies', function($scope,$http,$cookies){
$scope.createInsert = function(){
var data = {};
data.Title = $scope.Title;
data.file = $scope.file;
$http.post('http://localhost:3000/upload', JSON.stringify(data)).then() //callback
}
}]);
sever side:
exports.saveDatatry=function(request, response){
console.log(request.body);
var file = request.files.file;
var hash = hasher();
var stream = fs.createReadStream(file.path)
var mimetype = mime.lookup(file.path);
console.log(stream);
var req;
if (mimetype.localeCompare('image/jpeg')
|| mimetype.localeCompare('image/pjpeg')
|| mimetype.localeCompare('image/png')
|| mimetype.localeCompare('image/gif')) {
req = client.putStream(stream, hash+'.png',
{
'Content-Type': mimetype,
'Cache-Control': 'max-age=604800',
'x-amz-acl': 'public-read',
'Content-Length': file.size
},
function(err, result) {
var savePerTry = new personal({
Title: request.body.Title,
file: req.url
});
savePerTry.save(function(error, result) {
if (error) {
console.error(error);
} else {
console.log("saved!");
response.redirect('http://localhost:8080/tryinsert.html');
};
})
});
} else {
console.log(err);
}
}
What I need to do?
Thanks,
Here's your problem:
function(err, result) {
var savePerTry = new personal({
Title: request.body.Title,
file: req.url
});
Every time you write something like:
function(err, result) {
then the very next line should be:
if (err) {
// ...
}
When you don't handle the errors you will get 500 internal server errors and you will not know what's wrong.
Always handle errors.
I have a problem with node.js and express, I try to get infos from a post coming from an html file, and the problem is that when I do a console.log of my request i don't have any information inside my req.body.
I did a console.log(req.body) at the beginning of my app.post("/render_pdf" ....) and all i've got is a empty object.
I don't know if it's coming from my .html or my server.js but i don't understand where the problem is coming from. I used multer to upload a pdf based on a html select and it's working .. so i don't have any solutions on this.
my html (with a bit of php) :
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ebook-stage</title>
<link href="public/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php
$pdo=new PDO('mysql:host=localhost; dbname=ebook-stage; charset=utf8',
'root', '');
$statement=$pdo->prepare("SELECT * FROM publication");
$statement->execute();
?>
<div class="jumbotron">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
<form method="POST" action="http://localhost:8090/create_pdf" enctype="multipart/form-data">
<label for="extractor">Extracteur PDF</label>
<br><select class="form-control" name="extractor" id="extractor">
<option name="pdf2json" value="pdf2json">PDF2JSON</option>
<option name="pdfextract" value="pdfextract">PDFEXTRACT</option>
<option name="textract" value="textract">TEXTRACT</option>
</select>
<br><label for="file">Upload Pdf</label>
<input id="file" type="file" name="file">
<br><input type="submit" name="submit" id="submit" class="exec btn btn-success" value="Exécuter">
</form>
</div>
<div class="col-md-3">
<form method="POST" action="http://localhost:8090/render_pdf">
<label for="require">PDF a afficher</label>
<br><select class="form-control" name="require" id="require">
<?php while ($rendername = $statement->fetchObject()):?>
<option name="<?= $rendername->name ?>"><?= $rendername->name ?></option>
<?php endwhile; ?>
</select>
<?php while ($rendername = $statement->fetchObject()):?>
<input type="hidden" name="<?= $rendername->id ?>" id="id">
<?php endwhile; ?>
<br><input type="submit" name="envoi" id="envoi" class="exec btn btn-success" value="Afficher">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
my pdf-rest.js :
var mysql = require('mysql');
var bodyParser = require('body-parser');
var request = require('request');
var jsonParser = bodyParser.json();
var http = require('http');
var fs = require('fs');
var Promise = require('bluebird');
var multer = require('multer');
var textract = require('textract');
var pdf_extract = require('pdf-extract');
var PDFParser = require("pdf2json");
var pdfParser = new PDFParser();
var inspect = require('eyes').inspector({maxLength:20000});
var optionsExtract = {
type: 'ocr' // perform ocr to get the text within the scanned image
};
var express = require('express');
module.exports = function(app){
function requireDB(){
connection.connect();
connection.query('SELECT * FROM publication WHERE id = 105', function(err, rows, fields){
console.log(err);
res.end(rows[0].id+rows[0].name);
});
}
app.post('/render_pdf', jsonParser, function (req, res) {
console.log(req);
res.end('affichage pdf');
});
var destination = "uploads";
app.post('/create_pdf', jsonParser, function (req, res) {
console.log(req.body);
var connection = mysql.createConnection({
user: 'root',
password: '',
host: 'localhost',
port: 3306,
database: 'ebook-stage'
});
var filename = "" + Date.now() + ".pdf";
var filePath = "C:\\wamp64\\www\\ebook-stage\\backend\\rest\\uploads\\" + filename;
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, destination);
},
filename: function (req, file, cb) {
cb(null, filename);
}
});
var upload = multer({storage: storage}).single('file');
function uploadFile() {
console.log('entering upload file');
var uploadFilePromise = new Promise(function (resolve,reject) {
upload(req, res, function (err) {
if (err) {
reject(err);
res.end('error uploading file')
}
else{
console.log('upload resolve');
res.end('pdf uploaded');
console.log(req.body);
resolve(req);
}
});
});
return uploadFilePromise;
}
function insertDB(pdfObject) {
connection.connect();
var insertPublication = {name: pdfObject.originalFilename};
new Promise(function (resolve, reject) {
connection.query('INSERT INTO publication SET ?', insertPublication, function (err, res) {
if (err) {
reject(err);
}
else {
console.log('insertDB publication');
console.log(res);
resolve(res['insertId']);
}
});
}).then(function (pubId) {
pdfObject.text.forEach(function (text) {
var insertContent = {type: 'TXT', content: text};
new Promise(function (resolve, reject) {
connection.query('INSERT INTO content SET ?', insertContent, function (err, res) {
if (err) {
console.log(err);
reject(err)
}
else {
console.log('insertDB content');
console.log(res);
resolve(res['insertId']);
}
});
}).then(function (insertBlock) {
var blockid = {contentid: insertBlock};
new Promise(function (resolve, reject) {
connection.query('INSERT INTO block SET ?', blockid, function (err, res) {
if (err) {
console.log(err);
reject(err);
}
else {
console.log('insertDB block');
console.log(res);
resolve(res['insertId']);
}
});
}).then(function (blockId) {
var linkpublicationids = {blockid: blockId, publicationid: pubId};
connection.query('INSERT INTO linkpublication SET ?', linkpublicationids, function (err, res) {
if (err) {
console.log(err);
return err
}
else {
console.log('insertDB linkpublication');
console.log(res);
}
});
})
});
});
}).catch(function () {
connection.end(function (err) {
console.log(err);
})
});
}
function textractPdf(originalFilename) {
console.log('TEXTRACT PDF');
var textBlockPromise = new Promise(function (resolve, reject){
textract.fromFileWithPath(filePath, function (error, text) {
var result = [{originalFilename: originalFilename}];
if (error) {
console.log('Text is not parsed');
reject(error);
}
else {
console.log('Text is parsed');
result[0].text = [];
result[0].text.push(text);
resolve(result[0]);
console.log('after resolve textract')
}
});
});
console.log('exiting textract');
return textBlockPromise;
}
function extractPdf(originalFilename) {
console.log('EXTRACT PDF');
var textBlockPromise = new Promise(function (resolve, reject){
var result = [{originalFilename: originalFilename}];
processor = pdf_extract(filePath, optionsExtract, function (err) {
if (err) {
console.log('error extract');
reject(err);
}
});
processor.on('complete', function (data) {
var resultsplited = data.text_pages[0].split('\n');
result[0].text = [];
resultsplited.forEach(function(text){
result[0].text.push(text);
});
resolve(result[0]);
});
processor.on('error', function (err) {
console.log('error extract');
inspect(err, 'error while extracting pages');
reject(err);
});
});
return textBlockPromise;
}
function convertPdf2json(originalFilename){
console.log('EXTRACT PDF2JSON');
var textBlockPromise = new Promise(function (resolve, reject){
var result = [{originalFilename: originalFilename}];
result[0].text = [];
pdfParser.on("pdfParser_dataError", function(errData){
reject(errData);
});
pdfParser.on("pdfParser_dataReady", function(pdfData){
pdfData.formImage.Pages.forEach(function(page){
page.Texts.forEach(function(text){
var textparsed = decodeURIComponent(text.R[0].T);
result[0].text.push(textparsed);
});
});
resolve(result[0]);
});
pdfParser.loadPDF(filePath);
});
return textBlockPromise
}
function selectExtractor(req){
console.log(req.body.extractor);
var extractorPromise = new Promise(function (resolve){
if(req.body.extractor == 'textract'){
resolve (textractPdf(req.file.originalname));
console.log('extractor end');
}
else if(req.body.extractor == 'pdfextract'){
resolve(extractPdf(req.file.originalname));
console.log('extractor end');
}
else if (req.body.extractor == 'pdf2json'){
resolve(convertPdf2json(req.file.originalname));
console.log('extractor end');
}
});
return extractorPromise;
}
uploadFile().then(selectExtractor).then(insertDB);
});
};
my server.js :
var express = require('express');
var app = express();
require('./pdf-rest.js')(app);
app.listen(8090);
Just try to update your server file to this actually to use req.body we need to register the middle-ware to all our routes.
var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
var app = express();
require('./pdf-rest.js')(app);
app.listen(8090);
As you use multipart/form-data in your form, the body-parser probably won't help here. See body-parser home page:
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
I have no experience with multer, but try using it as it's described in their documentation:
var upload = multer({ dest: 'uploads/' })
app.post('/create_pdf', upload.single('file'), function (req, res, next) {
// req.file is the uploaded file
// req.body will hold the text fields, if there were any
})
html:
<form method='post' action='upload_bg' enctype="multipart/form-data">
<input type='file' name='fileUploaded'>
<input type='submit'>
My index.js
app.route('/upload_bg')
.post(function (req, res) {
var fstream;
req.busboy.on('file', function (fieldname, file, filename) {
console.log(filename);
fstream = fs.createWriteStream(__dirname + '/imgs/' + "latest_upload.jpg");
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
});
My variables:
var express = require('express');
var busboy = require('connect-busboy');
var path = require('path');
var fs = require('fs-extra');
So the user clicks the button, selects an image, and selects submit. This hit's my route upload_bg. I've had it working before, and I changed a few things around but I'm unable to understand why it isn't working. I look in the network tab and the request is just pending indefinitely.
Here is my simple solution using express-fileupload module:
First intall express fileupload module using following command:
npm install express-fileupload
HTML page code:
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='http://localhost:3000/upload_bg'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
node server code:
server.js:
var express=require('express');
var app = express();
var fileUpload = require('express-fileupload');
// default options
app.use(fileUpload());
app.post('/upload_bg', function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
// Make sure 'imgs' folder is already created inside current directory otherwise it will throw error where this server.js file is placed
sampleFile.mv(__dirname + '/imgs/latest_upload.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
app.listen(3000,function(){
console.log("App listening on port 3000")
});
Hope this will help. For complete code refer https://github.com/richardgirges/express-fileupload
I would personally re-style your code a little bit. And I would use ajax. Here is some example code:
index html:
<button class="btn btn-lg upload-btn" type="button">Upload image</button>
<input id="upload-input" type="file" name="uploads[]" multiple="multiple">
client js:
This can/should be inside of index.html
$('.upload-btn').on('click', function (){
$('#upload-input').click();
$('.progress-bar').text('0%');
$('.progress-bar').width('0%');
});
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
// create a FormData object which will be sent as the data payload in the
// AJAX request
var formData = new FormData();
// loop through all the selected files and add them to the formData object
for (var i = 0; i < files.length; i++) {
var file = files[i];
// add the files to formData object for the data payload
formData.append('uploads[]', file, file.name);
}
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!\n' + data);
},
});
}
});
server js:
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var l;
//... other code here
app.get('/upload', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/upload', function(req, res){
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/uploads');
form.on('file', function(field, file) {
fs.readdir('uploads/', function(err, items) {
console.log(items.length);
l = items.length
console.log(l);
fs.rename(file.path, "uploads/"+l+".jpg", function(err) {
if ( err ) console.log('ERROR: ' + err);
});
});
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
Hope this helps!
I have this code in order to upload files with node.js:
app.use(express.bodyParser());
// or, as `req.files` is only provided by the multipart middleware, you could
// add just that if you're not concerned with parsing non-multipart uploads,
// like:
app.use(express.multipart());
app.get('/',function(req,res){
fs.readFile('uploadHTML.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.post('/upload',function(req,res)
{
console.log(req.files);
fs.readFile(req.files.displayImage.path, function (err, data) {
// ...
var newPath = __dirname;
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});
Here is the HTML file:
<html>
<head>
<title>Upload Example</title>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/upload"
method="post">
<input type="file" id="userPhotoInput" name="displayImage" />
<input type="submit" value="Submit">
</form>
<span id="status" />
<img id="uploadedImage" />
</body>
</html>
When I upload the file, it gives me the next error:
TypeError: Cannot read property 'displayImage' of undefined at c:\NodeInstall\nodejs\express.js:42:22 at callbacks (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:164:37) at param (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:138:11) at pass (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:33:10) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\NodeInstall\nodejs\node_modules\express\lib\middleware.js:30:5) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)
What could be the reason?
I do recommend you to use awesome module https://github.com/domharrington/fileupload for handling file uploads in node/express.
var fileupload = require('fileupload').createFileUpload('/uploadDir').middleware
app.post('/upload', fileupload, function(req, res) {
// files are now in the req.body object along with other form fields
// files also get moved to the uploadDir specified
})
Another way to upload files could be using something like this
Jade template
form.data(action='/user/register', method='post', class="long-fields", enctype='multipart/form-data')
input(type="text" name="name")
input(name='fileLogo', type='file')
input(type="submit" value="Register")
Controller
formidable = require('formidable'); //file upload handling via form
uuid = require('node-uuid'); //Unique ID
path = require('path'); //Path compiler
fs = require('fs'); //FileSystem
var form = new formidable.IncomingForm();
form.keepExtensions = false;
form.maxFieldsSize = 2 * 1024 * 1024; //2mb
form.parse(req, function(err, fields, files) {
console.log(fields);
console.log(files);
fs.readFile(files.fileLogo.path, function (err, data) {
var pathNew = __dirname + '/../../uploads/' + uuid.v1() + path.extname(files.fileLogo.name)
fs.writeFile(pathNew, data, function (err) {
console.log('uploaded', pathNew);
});
});
res.send(jade.renderFile( settings.pathLess + prefix + '/register.jade', {
req : req
}));
});