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.
Related
I'm trying to create a simple node server that sends emails with nodemailer
let app = require('express')();
app.use(require('body-parser').urlencoded());
const CONTACT_ADDRESS = 'email#email.com';
var mailer = require('nodemailer').createTransport({
service: 'mail.ee',
auth: {
user: 'test#test.com',
pass: 'password',
}
});
app.post('/contact', function(req, res) {
mailer.sendMail({
from: req.body.from,
to: '[CONTACT_ADDRESS]',
subject: req.body.subject || '[No subject]',
html: req.body.message || '[No message]',
}, function(err, info) {
if (err) return res.status(500).send(err);
res.json({success: true});
})
});
//Service is listening to port 3000
app.listen(3000, function(){
console.log("Service is running on port 3000...");
});
and the contact form is as follows:
<form method="post" action="http://localhost:3000/contact">
<label>Your e-mail</label>
<input type="text" name="from">
<label>Subject</label>
<input type="text" name="subject">
<label>Message</label>
<textarea name="body"></textarea>
<input type="submit" value="Submit">
</form>
When ever I press on submit button I get:
JSON.stringify(value); TypeError: Converting circular structure to
JSON
What does it mean? How can I overcome it?
res.send method trying to stringify your err object, but your err object cant be stringified, because not a standard error object. Try to output this err object to see and decide how to handle it.
For example you can use
if (err) return res.status(500).send(err.reason);
istead
if (err) return res.status(500).send(err);
I have a CMS for a food automation system and I'm going to add a part for upload pictures for foods:
<form method="post" enctype="multipart/form-data" action="/upload">
<td><input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file"></td>
<td><input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" ></td>
</form>
I wrote this code for making a POST request in Express.js:
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
targetPath = path.resolve('./uploads/image.png');
if (path.extname(req.files.file.name).toLowerCase() === '.png') {
fs.rename(tempPath, targetPath, function(err) {
if (err)
throw err;
console.log("Upload completed!");
});
} else {
fs.unlink(tempPath, function () {
if (err)
throw err;
console.error("Only .png files are allowed!");
});
}
});
However when I define this app.use, I get an error:
Middleware: app.use(express.bodyParser({uploadDir:'/img'}));
Error: Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
When I define a middleware like this :
app.use(bodyParser({uploadDir:'/img/'}));
I don't have any errors but my code doesn't work correctly .
This solution worked for me :
multer = require('multer'),
upload = multer({ dest: 'views/img' });
app.post('/upload',upload.single('file'), function (req, res) {
});
And my form HTML form :
<form method="post" enctype="multipart/form-data" action="/upload">
<input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file">
<input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" >
</form>
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.
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.
Context: Want to insert data in mongoDB database from node.js
Problem Statement: I am trying to insert data in the mongoDB database but thrown an error. Cant find it.
Present Output: Reference error
Attach Code:
filter.js
var server = require('http'),
express = require('express'),
http = require('http'),
fs = require('fs');
filter = express(),
io = require('socket.io'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/filter_CheckBoxSchema', function(err){
if(err){
console.log(err);
} else{
console.log('Connected to mongodb!');
}
});
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
var filter_CheckBoxSchema = mongoose.Schema({
name: String,
type: Boolean,
created: {type: Date, default: Date.now}
});
var Filter = mongoose.model('Store', filter_CheckBoxSchema);
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
new Filter({
name: request.body.name,
type: request.body.gender,
}).save(function(err, doc){
if(err)
{
throw err;
}
else
response.send('Successfully inserted!!!');
});
});
index.html
<html>
<head>
<title>Please enter your details</title>
</head>
<body>
<h3>Please enter your details</h3>
<p>Please register below!!!</p>
<form action="filter.js" method="POST">
Name: <input type="text" name="Name" />
<br /><p></p>
Gender:
<br />
<input type="radio" name="gender"/> Male
<br />
<input type="radio" name="gender"/> Female
<p></p>
Interest: (Check all that apply)
<p>
</p>
<input type="checkbox" name="breakfast"/> Breakfast
<br/>
<input type="checkbox" name="Lunch"/> Lunch
<br />
<input type="checkbox" name="Evening Snacks"/> Evening Snacks
<br />
<input type="checkbox" name="Dinner"/> Dinner
<br />
<p></p>
<input type="submit" name="submit" value="Register!!!" />
</form>
</body>
</html>
Output:
C:\node\people discovery app>node filter.js
Connected to mongodb!
C:\node\people discovery app\filter.js:152
name: request.body.name,
^
ReferenceError: request is not defined
at C:\node\people discovery app\filter.js:152:9
at fs.js:271:14
at Object.oncomplete (fs.js:107:15)
It appears you don't completely grasp the asynchronous nature of javascript. Variables passed to a function only exist in that function's scope. See this commented code:
var express = require('express'),
http = require('http'),
fs = require('fs'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/filter_CheckBoxSchema', function(err){
if(err){
console.log(err);
} else{
console.log('Connected to mongodb!');
}
});
//Lets read our html file only once, at the very beginning when we first start our nodejs process
fs.readFile('./index.html', function (err, html) {
//Now in here there are two variables which are accessible, `err` and `html`
if (err) {
throw err;
}
//Create our schema before starting server
var filter_CheckBoxSchema = mongoose.Schema({
name: String,
type: Boolean,
created: {type: Date, default: Date.now}
});
//And now the model as well
var Filter = mongoose.model('Store', filter_CheckBoxSchema);
//Now lets start our server
http.createServer(function(request, response) {
//The code here is called whenever a new http request is sent to the server
//There are two variables accessible here, one is `request` which contains
//data about the original request, while `response` is an object with methods
//allowing you to respond
//Here we check what kind of method the browser is using, if its POSTing
//data then we create a filter from the body
if (request.method == "POST") {
new Filter({
name: request.body.name,
type: request.body.gender,
}).save(function(err, doc){
if(err)
{
throw err;
}
else {
response.send('Successfully inserted!!!');
}
});
}
else {
//This must have been a GET request, lets just send `html` instead
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}
}).listen(8000);
});