I am trying to use an upload program to upload my files. The code that I use is
app.post('/photos',loadUser, function(req, res) {
var post = new Post();
req.form.complete(function(err, fields, files) {
if(err) {
console.log(err);
next(err);
} else {
ins = fs.createReadStream(files.file.path);
ous = fs.createWriteStream(__dirname + '/public/uploads/photos/' + files.file.filename);
post.filename=files.file.filename;
post.file=files.file.path;
util.pump(ins, ous, function(err) {
if(err) {
next(err);
} else {
post.save(function(err,docs) {
req.flash('info', 'information Saved');
res.redirect('/photos');
});
}
});
}
});
});
When I remove loadUser method everything is working fine, but when I use the loadUser method it is giving me an error. The console information of the error is:
Error: parser error, 0 of 4344 bytes parsed
at IncomingForm.write (/home/darhamid/node_modules/formidable/lib/incoming_form.js:141:17)
at IncomingMessage.<anonymous> (/home/darhamid/node_modules/formidable/lib/incoming_form.js:91:12)
at IncomingMessage.emit (events.js:67:17)
at HTTPParser.onBody (http.js:121:23)
at Socket.ondata (http.js:1349:22)
at TCP.onread (net_uv.js:312:27)
The error is caused only when i use loadUser function, if i remove the loadUser Funciton everything is working fine.
I don't know the reason behind this and am stuck. Can anyone help me please?
See this github issue : https://github.com/felixge/node-formidable/issues/34
Another possible cause for the problem is in this line:
request.setEncoding( "utf8" );
You are trying to perform database operation before everything, which is creating problems for you. Try the following code:
app.post('/potos', function(req, res, next) {
//req.form.pause();
req.form.complete(function(err, fields, files) {
if(err) {
next(err);
} else {
ins = fs.createReadStream(files.file.path);
ous = fs.createWriteStream(__dirname + '/public/uploads/photos/' + files.file.filename);
var post = new Post();
post.filename=files.file.filename;
post.file=files.file.path;
post.created_at = new Date();
post.user_id = req.session.user_id;
function postCreationFailed() {
req.flash('error', 'Unable to Download ');
res.render('photos/new', {
locals: {
post: new Post(),currentUser: req.session.user_id
}
});
}
util.pump(ins, ous, function(err) {
if(err) {
next(err);
} else {
console.log('\nuploaded %s to %s', files.file.filename, files.file.path);
post.save(function(err) {
if (err)
return postCreationFailed();
req.flash('info', 'photos Succesfully Uploaded');
res.redirect('/user/photos/'+post.user_id);
});
}
});
}
});
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
Good luck...
Related
My res.json in my first block of code works, but in the else part of my if statement, it does not. The block that doesnt work, checks for a record in a database then im trying to return the response but im not receiving it.
I've checked and the response is a string, I thought it would have worked as the top part of the code successfully returns the string and it shows in dialogflow (where im trying to return it)
The response is successfully consoled right before the res.json but I do not receive it from the source of the request.
code:
app.post('/webhook/orderinfo', (req, res) => {
const intent = req.body.queryResult.intent.displayName;
const domain = "chatbotdemo.myshopify.com";
const order = req.body.queryResult.parameters["number-sequence"];
if (intent.includes('Order Number')) {
url = "https://test-hchat.com/api/orders/" + domain + "/" + order;
request(url)
.then(function (response) {
order_res = JSON.parse(response)
order_res["fullfillmentText"] = "Hi, Please find your order details below:";
res.json({
"fulfillmentText": JSON.stringify(order_res)
})
})
.catch(function (err) {
console.log(err)
});
// THIS PART DOESNT RETURN THE RESPONSE.
} else {
const domain = 'testStore'
db.getClientsDialog(domain, intent, (response) => {
const fullResponse = response.response
res.json({
fullResponse
})
})
}
});
The database code:
getClientsDialog: function (domain, intent, callback) {
MongoClient.connect('mongodb://efwefewf#wefwef.mlab.com:15799/wefwef', function (err, client) {
if (err) throw err;
var db = client.db('asdsad');
db.collection('dialog').findOne({ domain: domain, intent: intent }, function (err, doc) {
if (!err) {
callback(doc)
} else {
throw err;
callback(err)
}
client.close();
});
console.dir("Called findOne");
});
}
Could it be because this second use of the res.json in the else statement, is trying to call the db first and therefore the link is lost to send the data back?
I have a Node application, within which I am using Graphics Magick to do some image/pdf manipulation.
I have the following code which calls mosaic() to combine a pdf and png. If I export the result as a png then the process is successful. However if I try to export the result as a pdf then the resulting pdf file does have a size, but opening it shows that there is nothing to see, it appears to be blank. No errors are thrown.
var newFileName = "result.pdf";
gm()
.in('-page', '+0+0')
.in('C:\\Code\\ProjectName\\src\\api\\test\\TestTemplatePDF.pdf')
.in('-page', '+103+70')
.in('C:\\Code\\ProjectName\\src\\api\\test\\pic1.png')
.mosaic()
.stream('pdf', (err, stdout, stderr) => {
if (err) console.log('stream error', err);
console.log('stream');
var writeStream = fs.createWriteStream('./etc/' + newFileName);
stdout.pipe(writeStream);
stderr.on('end', () => {
fs.readFile('./etc/streamError.txt', (err, data) => {
console.log('reading errorStream');
// if (err) console.error(err);
if (err) {
console.log('We found an error reading streamError.txt', err);
res.send(err);
} else if (data.length !== 0) {
console.log('streamError.txt should contain a detailed error message', data);
res.send(data);
} else {
console.log('streamError.txt contains no errors');
}
});
});
stdout.on('end', () => {
fs.readFile('./etc/' + newFileName, (err, data) => {
if (err) {
console.log("stdout error: " + err);
res.end();
} else {
console.log('Successfully read our new image file');
}
})
})
})
Output/console shows:
stream
reading errorStream
streamError.txt contains no errors
successfully read our new file
In the end this problem went away when I converted the pdf to a png before editing.
Presumably the conclusion is that when using mosaic() that they need to be the same type.
I'm using SailsJS as an API with Waterline connected to a MongoDB. I'm trying to put together an endpoint to edit existing DB entries but can't seem to get it to work and I'm hitting a wall as to why.
My route:
'post /edit/safety/:id': {
controller: 'SafetyController',
action: 'editSafety'
},
My controller function:
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOneById(id).then((err, safety) => {
if (err) {
res.send(500, err);
return;
}
if (!safety) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
safety.save((err, updatedSafety) => {
if (err) {
re.send(500, err);
return;
}
res.send(200, updatedSafety);
});
});
},
Any push in the right direction would be greatly appreciated.
I don't recognize the Safety.findOneById method - is this something you have custom built? If not, then it is likely your problem.
Try swapping it for either:
Safety.findOne(id)
or
Safety.findOne({id: id})
Note that the returned object will be a model instance if the record exists, and undefined otherwise. If you decide to go with Safety.find instead then the returned value will be an array containing all models matching the query.
Looks like the main issue was transposing the response and err objects. It was successfully completing the query, but loading it into the err object which gets caught and a 500 error is thrown. So I changed that and simplified in a few other places.
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOne(id).then((response, err) => {
var safety = response;
if (err) {
res.send(500, err);
return;
}
if (!response) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
Safety.update({
id: id
}, safety)
.then((result) => {
res.json(200, 'Ok!');
})
.catch((err) => {
sails.log.error('SafetyController.editSafety', err);
})
});
},
I need to access a mean.js web site page with phantomjs. The problem is I dont know what to include in the header to make it happen.
I can authenticate using http.request and get back the user object. But then I need to somehow take that information and place it in the phantomjs header to allow access to the page.
Here is some code:
'use strict';
var phantom = require('node-phantom-simple');
phantom.create({ path: require('phantomjs').path }, function (err, browser) {
if (err) {
console.log(err);
}
else {
browser.createPage(function (err, page) {
if (err) {
console.log(err);
}
else {
//this is wrong - does not work with mean.js/passport authentication
var authentication_data = { 'Authorization': 'Basic ' + new Buffer('<user>:<password>').toString('base64') };
page.set('customHeaders', authentication_data, function (err) {
if (err) {
console.log(err);
}
else {
var htmlPath = 'http://localhost:3000/path-to-my-web-page';
var complete = false;
page.onConsoleMessage = function (msg) {
console.log('Console: %s', msg);
if (msg === 'the page is loaded') complete = true;
};
return page.open(htmlPath, function (err, status) {
console.log('opened page ', status);
if (err) {
console.log('page.open', err);
}
else {
console.log('opened ' + htmlPath);
//stuff happens here after page is loaded
}
});
}
});
}
});
}
});
I am missing the piece that says it is ok to access the page.
Thanks for your help!
I am new to rethinkdb.
When I try out the sample code in https://github.com/rethinkdb/rethinkdb-example-nodejs/tree/master/todo-angular-express
function create(req, res, next) {
var todo = req.body;
todo.createdAt = r.now(); // Set the field `createdAt` to the current time
r.table('todos').insert(todo, {returnVals: true}).run(req._rdbConn, function(error, result) {
if (error) {
handleError(res, error)
}
else if (result.inserted !== 1) {
handleError(res, new Error("Document was not inserted."))
}
else {
res.send(JSON.stringify(result.new_val));
}
next();
});
}
I got the following error:
500 Internal Server Error
{"error":"return_vals renamed to return_changes in:\nr.table(\"todos\").insert({title: r.json(\"\"abcde\"\"), completed: r.json(\"false\"), createdAt: r.now()}, {returnVals: true})\n
And then I tried out the sample code in http://rethinkdb.com/docs/examples/node-todo/
function create(req, res, next) {
var todo = req.body; // req.body was created by `bodyParser`
todo.createdAt = r.now(); // Set the field `createdAt` to the current time
r.table('todos').insert(todo, {returnChanges: true}).run(req._rdbConn, function(error, result) {
if (error) {
handleError(res, error)
}
else if (result.inserted !== 1) {
handleError(res, new Error("Document was not inserted."))
}
else {
res.send(JSON.stringify(result.changes[0].new_val));
}
next();
});
}
I got the following error:
500 Internal Server Error
{"error":"Unrecognized optional argument returnChanges. in:\nr.table(\"todos\").insert({title: r.json(\"\"abcde\"\"), completed: r.json(\"false\"), createdAt: r.now()}, {returnChanges: true})\n "}
It seems that rethinkdb have changed returnVals to return_changes / returnChanges, and the argument of insert().
And I have the problem fixed when I used return_changes.
What is the right way to work on insert in latest version?
Do rethinkdb always changes its syntax?
this is indeed a bug in the example code. I've opened https://github.com/rethinkdb/rethinkdb-example-nodejs/issues/3 so we can fix it.
Your second problem with returnChanges not being recognized might come from using an old RethinkDB node driver. Have you tried updating the driver? http://rethinkdb.com/docs/install-drivers/javascript/