When I am posting a picture from my electron app to blob storage, sometimes it works, and other times I get this error on my terminal:
When I was first working on this app, this problem never showed up, until a week ago. It occurred without making any changes to this part of the app. Any idea on what could cause it.
The electron app goes white, and the dev tools are disconnected.
Here is the code:
var azure = require('azure-storage');
var blobSvc = azure.createBlobService('*connection keys inside here*');
function createBlob() {
blobSvc.createContainerIfNotExists('photos', {publicAccessLevel : 'blob'}, function(error, result, response){
if(!error){
console.log(response);
}
});
console.log("creating image for student#: " + stud_id);
blobSvc.createBlockBlobFromStream('photos', stud_id + '.jpg', toStream(imgData), imgData.size, function(error, result, response){
if(!error){
console.log("file upload: \n" + JSON.stringify(result) + " \n" + JSON.stringify(response));
createPerson();
}
else if (error) {
console.log("error: " + JSON.stringify(error));
}
});
}
In your code, you actually call the createBlockBlobFromStream immediately, probably without container having created. This may cause the problem.
So, you would need to put them within the callback of the createContainerIfNotExists function:
blobSvc.createContainerIfNotExists('photos', {publicAccessLevel : 'blob'}, function(error, result, response) {
if(!error) {
console.log(response);
console.log("creating image for student#: " + stud_id);
blobSvc.createBlockBlobFromStream('photos', stud_id + '.jpg', toStream(imgData), imgData.size, function(error, result, response) {
if(!error) {
console.log("file upload: \n" + JSON.stringify(result) + " \n" + JSON.stringify(response));
createPerson();
} else {
console.log("error: " + JSON.stringify(error));
}
});
}
});
Related
I'm using mongoDB to get back all of my collections with:
rawData = db.collection('Forecasts').find({});
After getting the collection I want to return this via res.json() function to the client side. how can i return it.
Adding my Server side code (using Express and Node JS):
router.post('/forecastHistory', (req, res, next) => {
var rawData;
var forecasts = [];
// Connection url
var url = 'mongodb://localhost:27017/SimplyForecastDB';
// Connect using MongoClient
MongoClient.connect(process.env.MONGODB_URI || url, (err, db) => {
if (err) {
console.log('Unable to connect to MongoDB server.');
}
console.log('Connected to MongoDB server.');
rawData = db.collection('Forecasts').find({}).forEach(function(doc) {
//console.log(JSON.stringify(doc, undefined, 2));
forecasts.push(doc);
});
db.close();
});
forecasts.forEach(function(doc){
console.log(JSON.stringify(doc, undefined, 2));
});
res.json(forecasts);
});
Adding my client side code here to (using js query and ajax):
$("#history").click(function() {
$.post('/forecastHistory', function(result) {
result.forEach(function(forecast){
$("#forecast").html(
"<p class=\"lead\">" + forecast.location + "</p>" +
"The summary of today: " + forecast.summary +
"<br>" + "Temp: " + forecast.temperature + " C" +
"<br>" + "It feels like: " + forecast.feelsLike + " C" +
"<br>" + "The Humidity: " + forecast.humidity + " %" +
"<br>" + "Wind Speed: " + forecast.windSpeed + " km/h" +
"<br>"
)
});
});
});
I would appreciate the help.
As per your code, it seems like you are sending the response to the client before you get the response from MongoDB, thus the 'forecasts' variable would be essentially empty. And since you want to send an array in response, use toArray instead of forEach
router.post('/forecastHistory', (req, res, next) => {
var rawData;
var forecasts = [];
// Connection url
var url = 'mongodb://localhost:27017/SimplyForecastDB';
// Connect using MongoClient
MongoClient.connect(process.env.MONGODB_URI || url, (err, db) => {
if (err) {
console.log('Unable to connect to MongoDB server.');
}
console.log('Connected to MongoDB server.');
rawData = db.collection('Forecasts').find({}).toArray(function(err,doc) {
if(err){
console.log(err);
return;
}
res.json(doc);
res.end();
});
db.close();
});
});
I'm trying to get some basic data from 2 different web api's (battery status and contacs) and write it into my .txt file
However when i do that, only one data gets written, as if it overwrites the other.
I know my code may look really bad, but im new to this and i really need help.
Code
//GET - Battery status
var options = {
host: 'www.w3.org',
port: 80,
path: '/work'
};
http.get(options, function (response) {
console.log("Response: " + response.statusCode);
console.log("Header:" + JSON.stringify(response.headers));
fs.writeFile("external-api.txt", "Responsecode:" + response.statusCode + "\nHeaders:" + JSON.stringify(response.headers))
}).on('error', function (e) {
console.log("Napaka!: " + e.message);
});
//GET ZAHTEVE - Contacts
var options = {
host: 'www.google.com',
port: 80,
path: '/work'
};
http.get(options, function (response) {
console.log("Odgovor: " + response.statusCode);
console.log("Header:" + JSON.stringify(response.headers));
fs.writeFile("external-api.txt", "Responsecode:" + response.statusCode + "\nHeaders:" + JSON.stringify(response.headers))
}).on('error', function (e) {
console.log("Napaka!: " + e.message);
});
Result
Anyone kind enough to tell me what am i doing wrong?
According to the Node.js docs:
fs.writeFile(file, data[, options], callback)
Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
So,what you're looking for is:
fs.appendFile(file, data[, options], callback)
Asynchronously append data to a file, creating the file if it does not
yet exist. data can be a string or a buffer.
Hope this helps
Why don't you use fs.appendFile .
fs.appendFile('message.txt', 'data to append', function (err) {
});
I am trying to update other user's information in Parse which is stored in User class.
Initially I tried following code:
1.
var user = Parse.User;
var query = new Parse.Query(user);
query.equalTo("name", userName); //to find specific user
query.first({
success: function(results) {
//update that user's details
results.set("name", newName);
results.save();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I got following error:
{code: 206, error: "Parse::UserCannotBeAlteredWithoutSessionError"}
2. Then I used Parse.Cloud.useMasterKey(), as I figured out that we can not edit other user's details. But it didn't work either. And master key overrides all security, so it was not a good idea to use this code.
3. So I tried following code:
var user = Parse.User;
var query = new Parse.Query(user);
query.equalTo("objectId", userName);
query.first({
success: function(results) {
results.set("name", newName);
results.save(null, { useMasterKey:true}).then(function(user) {console.log("updated!!!");}, function(error) {console.log(error); });
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
But I am getting '401 Unauthorized' error.
Does anyone know how to update other user's information in Parse? Any help would be greatly appreciated.
You should call fetch function after updated current user object. You can follow below sample:
var currentUser = Parse.User.current();
currentUser.set('name', 'New Name');
currentUser.save(null, {
success: function(user) {
currentUser.fetch();
},
error: function(user, error) {
alert('Failed to update object, with error code: ' + error.message);
}
});
I have recently set up node.js using Express and I created a simple HTML form using Jade. The form is to insert the data in a PostgreSQL database. The problem is that when I press submit on the form, everything is inserted on the database, but the HTML form is just hanging/lingering, and at some point it stops with No data received, ERR_EMPTY_RESPONSE. Sometimes it also inserts the data twice. I guess this is because the server side does not return a response, but I cannot see how (I am new to node.js).
The form has action="add_device" which is routed to routes/add_device.js. add_device.js looks like this:
var express = require('express');
var router = express.Router();
router.get('/', function(request, response, next) {
res.send('Nothing to see here. Move along.');
});
router.post('/', function(request, response, next) {
var db = require('../public/javascripts/db/insert');
var result = db.insertDevice(request, response);
return result;
});
module.exports = router;
The insertDevice function in my db module looks like this (it is exported with module.exports):
// Insert new QA device. Data arriving as a request from a HTML form.
insertDevice: function (request, response) {
// Input that is verified in the HTML form.
// Convert to proper format for PostgreSQL query.
var name = '\'' + request.body.name + '\'';
var ip_address = '\'' + request.body.ip_address + '\'';
var os = '\'' + request.body.os + '\'';
// Input that needs to be verified. Prepare for PostgreSQL query.
var mac_address;
var os_version;
request.body.mac_address == "" ? mac_address = 'NULL' : mac_address = '\'' + request.body.mac_address + '\'';
request.body.os_version == "" ? os_version = 'NULL' : os_version = '\'' + request.body.os_version + '\'';
var pg = require('pg'); // PostgreSQL module.
var td = require('./table_data') // Database constants.
var client = new pg.Client(request.app.get('postgreConnection'));
client.connect(function(err) {
if (err) {
return console.error('Could not connect to postgres', err);
}
var QUERY = "INSERT INTO " + td.QA_DEVICES.TABLE_NAME + "(" +
td.QA_DEVICES.COLUMN_NAME + ", " +
td.QA_DEVICES.COLUMN_MAC_ADDRESS + ", " +
td.QA_DEVICES.COLUMN_IP_ADDRESS + ", " +
td.QA_DEVICES.COLUMN_OS + ", " +
td.QA_DEVICES.COLUMN_OS_VERSION + ") VALUES(" +
name + ", " +
mac_address + ", " +
ip_address + ", " +
os + ", " +
os_version + ");";
client.query(QUERY, function (err, result) {
if (err) {
return console.error('Error running query: ' + QUERY, err);
}
console.log('Query performed: ' + QUERY);
client.end();
});
});
}
The 'Query performed' is always logged to console and data inserted into the database, but the form is still hanging. My questions are:
Is it the lack of response from the server that makes the form hang?
How can I "send a response back" to the front end?
Is it possible to route the front end to another page after insertion into the database? What is the best practice?
Yes, your request is receiving no response, so it is hanging.
In order to send a response, you can either send a blind acknowledgement right when the request is received (that is not dependent upon the success of the query and may be bad practice), or you can send it in the callback.
client.query(QUERY, function (err, result) {
if (err) {
// response.json({status: 'error'});
response.write('Error');
return console.error('Error running query: ' + QUERY, err);
} else {
// You can send json here too
// response.json({status: 'success'});
response.write('Success');
}
console.log('Query performed: ' + QUERY);
client.end();
});
If you want to go to another page, simply parse the incoming response on the client side and do a redirect. Using json is a good way to carry this out. You can also do a response.redirect(url) on the server side too, instead of sending back data. Have fun
I'm attempting to use Cloud Code on Parse to delete pre-existing rows as new rows are added.
This is the current code I've put together:
var queryGoals = new Parse.Query(Parse.Object.extend('Goal'));
queryGoals.include('user');
queryGoals.equalTo('user', request.user);
queryGoals.find({
success: function(results) {
console.warn('Query Returned: ' + results.length);
Parse.Object.destroyAll(results);
},
error: function(user, error) {
console.warn('Error ' + error.code + ': ' + error.message);
}
});
The console never shows the number of records returned (I assume because none are), nor any errors. The same code (with Parse.User.current() for the user filter, of course) returns the expected number of rows when run client-side.
Do queries operate differently when executed by Cloud Code, or have I overlooked something?
I filed a bug report with Parse and finally ended up finding out that the function was ending before the success function was executed since it was running asynchronously. I added in the proper promise structure to get it working as expected (Additional Details):
queryGoals.find(
{
useMasterKey: true,
success: function(results)
{
Parse.Object.destroyAll(results);
},
error: function(user, error)
{
console.warn('Error ' + error.code + ': ' + error.message);
}
}).then(
function(object)
{
// Do Post-Query Stuff Here
response.success();
},
function(error)
{
console.warn('Error ' + error.code + ': ' + error.message);
}
);