req.param.id brings "undefined" - javascript

Getting req.param undefined
Hi, I have a similar error to the one above.
server.get('/:file_id', function(req , res) {
var file_id = req.params.id;
console.log(file_id);
gfs.files.find({_id: file_id}).toArray(function (err, files) {
if (err) {
res.json(err);
}
if (files.length > 0) {
var mime = files[0].contentType;
var filename = files[0].filename;
res.set('Content-Type', mime);
res.set('Content-Disposition', "inline; filename=" + filename);
var read_stream = gfs.createReadStream({_id: file_id});
read_stream.pipe(res);
} else {
res.json(file_id+ ' This file does not exist.');
}
});
});
Below is a ejs file that gets file_id to server.
<div class="card card-body mb-3">
<%= file.filename %>
<form action="/:<%= file._id %>" method="get">
<input type="submit" value="DOWNLOAD" class="btn btn-primary btn-block">
</form>
</div>
What I get from this code is : "undefined This file does not exist."
I think the problem lies on req.params.id but am not sure where to fix.
Thank you.

Related

Schema in Mongoose and Gridfs

I am using Mongoose to upload files to database. I have no problems uploading files and even viewing the names of files stored in the database, the only problem is that I can't download or delete the files.
I don't have a clue why I can't download my files especially when I can actually retrieve the file's metadata (ID) by Gridfs. Here's my code.
const storage = new GridFsStorage({
url: mongoURI,
cache: true, // cache
file: (req, file) => {
return file.originalname + Date.now();
}
});
const upload = multer({ storage });
server.get("/upload", (req,res) =>{
res.render('upload');
});
// #route POST /upload
server.post('/upload', upload.single('file'), (req, res) => {
res.redirect("/");
});
server.get('/:file_id', function(req , res) {
var file_id = req.params.file_id;
gfs.files.find({_id: file_id}).toArray(function (err, files) {
if (err) {
res.json(err);
}
if (files.length > 0) {
var mime = files[0].contentType;
var filename = files[0].filename;
res.set('Content-Type', mime);
res.set('Content-Disposition', "inline; filename=" + filename);
var read_stream = gfs.createReadStream({_id: file_id});
read_stream.pipe(res);
} else {
res.json(file_id+ ' This file does not exist.');
}
});
});
Below is a ejs file that gets file_id to server.
<div class="card card-body mb-3">
<%= file.filename %>
<form action= "/delete<%= file._id %>" method="post">
<button class="delete">DELETE</button>
</form>
<form action="/<%= file._id %>" method="get">
<input type="submit" value="DOWNLOAD" class="btn btn-primary btn-block">
</form>
</div>
What I can see when I try to download the files is :
:62bb571d71c40d24ea68b589 This file does not exist.
And the url of the page is:
http://localhost:3000/62bb571d71c40d24ea68b589?

Upload and retrieve image using parse and back4app with nodejs and express

Maybe this is an already answered question but I can't seem to find the right answer for me. I can't see what's wrong with my code.
I have a form to upload the specifics of a vehicle such as route, price, a picture of the vehicle, etc. When I get the url of the image, it doesn't display anything
example image
Here's the code I use to post my form
//POST create vehicle
app.post('/createVehicle', async function(req, res, next){
const fileData = new Parse.File("VehiclePic", { base64: req.body.VehicleImg }, "image/png");
console.log(fileData);
let car = new Car();
const Vehicle = {
VehicleImg: fileData,
Name: req.body.Name,
description: req.body.description,
Price: parseInt(req.body.Price),
Route: req.body.Route,
PassengerAmount: parseInt(req.body.PassengerAmount)
}
try{
fileData.save().then(saved => {
car.set('Image', saved);
car.set('Name', Vehicle.Name);
car.set('Description', Vehicle.description);
car.set('Route', Vehicle.Route);
car.set('Price', Vehicle.Price);
car.set('PassengerAmount', Vehicle.PassengerAmount);
console.log("URL vehiculo " + saved.url());
car.save();
console.log("El vehiculo ha sido creado con exito!");
})
}catch(error){
console.error('error ' , error);
}
res.redirect('/');
});
The reason I don't use Vehicle.VehicleImg is because it returns me an undefined object.
Here's the code to get all data
const Car = Parse.Object.extend('Vehicle');
const query = new Parse.Query(Car);
app.get('/', async function(req, res) {
const VehicleInfo = [];
query.notEqualTo("objectId", null);
try {
const result = await query.find();
result.forEach(vehicle => {
const vehiclePic = vehicle.get('Image');
VehicleInfo.push({
VehicleID: vehicle.id,
VehicleImage: vehiclePic,
VehicleName: vehicle.get('Name'),
Description: vehicle.get('Description'),
Price: vehicle.get('Price'),
Rating: vehicle.get('Rating'),
Route: vehicle.get('Route'),
PassengerAmount: vehicle.get('PassengerAmount')
});
});
res.render('index', {
title: 'MainPage',
VehicleData: VehicleInfo
});
} catch (error) {
console.error('error fetching objects', error);
}
});
EDIT:this is the form, I'm using ejs.
<div class="createVehicle-section container">
<br>
<form method="POST" action="/createVehicle" enctype="multipart/form-data">
<div id="img">
<label for="VehicleImg">Seleccione la imagen:</label>
<input type="file" id="VehicleImg" name="VehicleImg" >
</div>
<br>
<div class="col-lg-12 row">
<div class="col-md-6">
<label for="VehicleName">Nombre del vehiculo</label>
<input type="text" id="VehicleName" name="Name">
<br>
<label for="DescriptionVe">DescripciĆ³n</label>
<input type="text" id="Descriptionve" name="description">
</div>
<div class="col-md-6">
<label for="PriceVe">Precio</label>
<input type="number" id="PriceVe" name="Price" min="0" max="9999">
<br>
<label for="RouteVe">Ruta</label>
<input type="text" id="RouteVe" name="Route">
</div>
</div>
<br>
<div class="col-md-6 container">
<label for="PassegerAmountVe">Cantidad de Pasajeros Permitida</label>
<input type="number" id="PassengerAmountVe" name="PassengerAmount" min="0" max="9999">
</div>
<br>
<div class="text-center">
<input class="btn btn-main btn-lg btn-shadow" type="submit" value="Guardar"/>
</div>
</form>
<br>
</div>
EDIT: Here's my multer code to upload it to a localstorage, and I need to upload it to back4app.
//Multer Image Storage
const storage = multer.diskStorage({
destination: './public/images/',
filename: function(req, file, cb){ //cb = callback
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init Upload
const upload = multer({
storage: storage,
limits:{fieldSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).single('VehicleImg');
Try the following code:
const upload = multer();
app.post('/createVehicle', upload.single('VehicleImg'), async function(req, res, next){
const fileData = new Parse.File("VehiclePic.png", [...req.file.buffer], "image/png");
console.log(fileData);
let car = new Car();
const Vehicle = {
VehicleImg: fileData,
Name: req.body.Name,
description: req.body.description,
Price: parseInt(req.body.Price),
Route: req.body.Route,
PassengerAmount: parseInt(req.body.PassengerAmount)
}
try{
fileData.save().then(saved => {
car.set('Image', saved);
car.set('Name', Vehicle.Name);
car.set('Description', Vehicle.description);
car.set('Route', Vehicle.Route);
car.set('Price', Vehicle.Price);
car.set('PassengerAmount', Vehicle.PassengerAmount);
console.log("URL vehiculo " + saved.url());
car.save();
console.log("El vehiculo ha sido creado con exito!");
})
}catch(error){
console.error('error ' , error);
}
res.redirect('/');
});

POST http://localhost:3000/upload 500 (Internal Server Error)

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.

Upload the files from the client browser into mongodb or disk?

I am facing problem with uploading files using node.js and express framework.
Below is my app.js code:
var express = require('express');
var fs = require('fs');
var busboy = require('connect-busboy');
var app = express();
app.use(busboy());
app.post('/fileupload', function(req, res) {
var fstream;
console.log(req.filename);
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/public/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
});
HTML code is
<form id="uploadForm" enctype="multipart/form-data" action="/fileupload" method="post">
<div class="azureD" style="display:none;">
<div class="pull-left">
<label class="labelTemp">Subscription ID</label>
<div class="clickRole addStoTabWid">
<input type="text" id="" placeholder="" style="border:none;width:100%;">
</div>
</div>
<div class="pull-left">
<label class="labelTemp">Upload .pem file</label>
<div class="clickRole addStoTabWid">
<input type="file" name="file" id="file" placeholder="" style="border:none;width:100%;">
</div>
</div>
<div class="modal-footer">
</br>
<input type="submit" value="Upload" name="submit">
</div>
</form>
I am getting the fallowing error in node.js console
TypeError: Cannot read property 'on' of undefined
at IncomingMessage.Readable.pipe (_stream_readable.js:495:7)
at C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\app.js:138:9
at callbacks (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\lib\router\index.js:161:37)
at param (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.methodOverride [as handle] (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:37:5)
at next (C:\Users\sangamesh.b\Desktop\release-2\Rapid_cloud\node_modules\express\node_modules\connect\lib\proto.js:190:15)
_stream_readable.js:505
dest.end();
^
TypeError: Cannot read property 'end' of undefined
at IncomingMessage.onend (_stream_readable.js:505:9)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickDomainCallback (node.js:381:11)
I have checked with everything i am not able fix this issue with my code please help me in this issue.
And i want to know any other alternative ways are there upload the file from the browser and store it into mongodb or localdisk
Use the following snippet. It works for you
var upload_path = path.resolve(__dirname + '../../../public/uploads');
var result = {
status: 0,
message: '',
data: ''
};
fs.readFile(req.files.file.path, function (err, data) {
var imageName = Date.now() +"_"+req.files.file.name;
/// If there's an error
if(err){
//error
} else {
var newPath = path.resolve(upload_path, imageName);
fs.writeFile(newPath, data, function (err) {
if(err) {
//error
} else {
fs.unlink(req.files.file.path, function() {
if (err) {
result.status = -1;
result.message = err;
} else {
result.data = imageName;
}
res.jsonp(result);
});
}
});
}
});
It looks like fstream is undefined as file.pipe() is causing the error. Make sure the filepath being passed into fs.createWriteStream() is correct.

How to add data to DB using a POST request in Node JS?

I tried to add a record to the database using a POST request in Node JS. I tried with the following,
<form action="/addDevice?deviceToken=" onsubmit="location.href = this.action + this.token.value; return false;" method="POST">
<input name="token" type="text" value="3456as7dssa65d56da78s9d9sd67"/><br>
<input type="submit" value="Add Device" class="btn btn-success"/><br>
</form>
in Node JS, I did,
app.post('/addDevice', function (req, res) {
device.addNewDevice(req.data.deviceToken, function (err, result) {
if (err) return res.json(err);
var msg = 'Added ' + result.affectedRows + ' rows.';
console.log('bode : ' + req.data.deviceToken);
// display all devices
device.getDevices(function (err, devices) {
if (err) return res.json(err);
res.render('device_view.html', {devices: devices, msg: msg});
});
});
});
When I'm running this I got the following error,
Cannot GET /addDevice?deviceToken=3456as7dssa65d56da78s9d9sd67
How can I fix this?
Thanks in Advance!

Categories

Resources