I am having problem posting to a function in my back-end (Node.js) from my front-end (AngularJS).
I keep getting a 404 error. Could someone see if there is something wrong with my code as I can't see what may be causing this.
Front end
MockUpMaker_v1/js/controller.js
// All photos've been pushed now sending it to back end
$timeout(function () {
$http.post('/MockUpMaker_v1/savePhotos', $scope.photosToPhp).then(function (success) {
$scope.generating = false;
$scope.generateBtn = 'Generate';
//creating mock up gallery
for (var x = 0; x < success.data.photos; x++) {
var file = '/MockUpMaker_v1/tmp/' + success.data.folder + "/out" + x + ".png";
$scope.gallery.push(file);
}
$scope.photosToPhp = [];
}, function (error) {
});
},
Back end
MockUpMaker_v1/server.js
app.post('/MockUpMaker_v1/savePhotos', function(req, res){
var folder = Math.random().toString(36).substr(2, 20);
var photos = req.body;
var counts = 0;
var callback = function(counts){
if(counts < photos.length){
saveBase64(photos[counts], folder, counts, callback);
}else{
// var counts = 0;
var response = {"folder": folder, "photos": photos.length};
res.send(response)
}
};
saveBase64(photos[counts], folder, counts, callback);
});
Full back-end
As requested
"use strict";
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var mkdirp = require('mkdirp');
var archiver = require('archiver');
var app = express();
var server = require('http').Server(app);
app.use(bodyParser.json({limit: '50mb'}));
app.use(express.static('/public'));
app.use(express.static('/js'));
app.use(express.static('/tmp'));
app.use(express.static('/img'));
app.use(express.static('/css'));
app.get('/', function(req, res){
res.sendFile(__dirname + 'views/form-mockup.html')
});
app.post('/MockUpMaker_v1/savePhotos', function(req, res){
var folder = Math.random().toString(36).substr(2, 20);
var photos = req.body;
var counts = 0;
var callback = function(counts){
if(counts < photos.length){
saveBase64(photos[counts], folder, counts, callback);
}else{
// var counts = 0;
var response = {"folder": folder, "photos": photos.length};
res.send(response)
}
};
saveBase64(photos[counts], folder, counts, callback);
});
app.post('MockUpMaker_v1/downloadZip', function(req, res){
var photos = req.body;
var out = photos[0];
var test = out.split('/');
var loc = test.pop();
var end = test.join('/');
console.log(end);
var outName = '/' + end + '/MockUp.zip';
var output = fs.createWriteStream(outName);
var archive = archiver('zip', {store: true });
var zip = function(photos, f){
for(var t = 0; t < photos.length; t++){
var file = 'mockUp' + t + '.jpg';
var from = '/' + photos[t];
archive.file( from, { name: file });
}
f();
};
output.on('close', function() {
var photos = req.body;
var out = photos[0];
var test = out.split('/');
var loc = test.pop();
var end = test.join('/');
res.send(end + '/MockUp.zip');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
zip(photos, f);
function f(){
archive.finalize();
}
});
server.listen(3000, function(){
console.log('sm2.0 server running');
});
function saveBase64(photo, folder, counts, callback){
var result = photo.split(',')[1];
var path = 'tmp/' + folder;
var filename = path + "/out" + counts + ".png";
mkdirp( path, function() {
fs.writeFile(filename, result, 'base64', function(error){
if (error) {
console.log('error saving photo');
}else{
console.log('photo saved');
counts++;
callback(counts);
}
});
});
}
And console printout
[nodemon] restarting due to changes... [nodemon] restarting due to
changes... [nodemon] starting node server.js sm2.0 server running
Inspect error
POST http://localhost:63342/MockUpMaker_v1/savePhotos 404 (Not Found)
In your Angular App, write the whole URL as the first argument of the $http.post function.
E.g. http://localhost:3000/MockUpMaker_v1/savePhotos
Related
I would like to send a picture from Ionic app to Laravel back-end, but I keep getting FileTransferError.FILE_NOT_FOUND_ERR (Code=1) in the app.
Taking picture works:
$scope.openCamera = function () {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: 1, // 0:Photo Library, 1=Camera, 2=Saved Photo Album
encodingType: 0 // 0=JPG 1=PNG
});
function onSuccess(FILE_URI) {
$scope.picData = FILE_URI;
$scope.$apply();
}
function onFail(message) {
alert('Error (' + message + ')');
}
}
}
But sending keeps throwing error:
$scope.send = function () {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var myImg = $scope.picData;
var options = new FileUploadOptions();
options.fileKey = "post";
options.chunkedMode = false;
options.fileName = 'someFileName.jpg';
options.mimeType = "image/jpeg";
var params = {};
params.token = localStorage.getItem('token');
options.params = params;
var ft = new FileTransfer();
ft.upload(myImg, encodeURI(SERVER + 'user/post'), win, fail, options);
}
}
I have noticed that when I look at the error.source that I can't find physically the file listed. I can't debug on browser (lack of camera) so I am deploying everything to my phone.
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
//alert("upload error target " + error.target);
}
well, i had this problem and i found a solution, a bit late, but will helps, someone:
var headers = {'Authorization':'Bearer '+ $localStorage.get('token')};
options.headers = headers;
Im trying to implement ngInfiniteScroll - Loading Remote Data on my app.
The Demo works fine & I was successfully getting the Reddit API, but cant get my list to work.
I am successfully hitting 200 server response & can see my data in the dev tool. These answers have been some help 1 & 2 but I'm still not fully sure on what to do.
EDIT (see angular factory edit):
This callback is now working and $http is going to success however I'm now getting Cannot read property 'length' of undefined
Angular Factory:
Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
// Edit - I changed this var from
// var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&jsonp=JSON_CALLBACK";
// to
var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data) {
console.log(data);
var items = data.children;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i].data);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
console.log('Reddit.prototype');
};
NodeJS Route:
app.get('/list', function (req, res) {
Found.find(function (err, post) {
if ( err ) {
res.send( err );
}
res.jsonp( post );
});
});
Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
// Edit - I changed this var from
// var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&jsonp=JSON_CALLBACK";
// to
var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data) {
console.log(data);
var items = data;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
console.log('Reddit.prototype');
};
Should fix it!
I have angular function which get pdf data from server:
printDocument: function (bundleId, policyId) {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
$resource(baseUrlPrint, {
bundleId: bundleId,
policyId: policyId
}, {
get: {
method: 'GET'
},
responseType:'arraybuffer',
cache: true
}).get().$promise.then(function(result) {
console.log(result);
var file = new Blob([result], {type: 'application/pdf'});
var fileURL = (window.URL || window.webkitURL).createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
}
When I check a result variable I see there is byte array contains pdf file. But when I open this file in Notepad++ I see that there is no pdf byte data but only:
[object Object]. Is something wrong with my Blob object?
In case the API Rest retrieves an array of bytes you can simply use this js function
(function() {
'use strict';
angular
.module('fileUtils')
.service('DownloadService', DownloadService);
DownloadService.$inject = ['$window'];
function DownloadService($window) { // jshint ignore:line
this.download = function (fileBytes, name, type) {
var fileName = '';
if (name) {
fileName = name + '.' + type;
} else {
fileName = 'download.' + type;
}
var byteCharacters = atob(fileBytes);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/' + type });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName);
} else {
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = fileName;
document.body.appendChild(a);
a.click();
}
};
}
})();
When i check all lists in table, and press delete button, A DELETE SERVICE will be called.(Using AngularJS)
Problem is, i am using a loop, and on successful delete and unsuccessful delete, i am getting alert multiple times.(No. of selection times)
And its not working properly, if place it out of loop because its Async Task.
Here is the code,
This is a controller which initiates a service.
$scope.confirmAction = function() {
var costsToDelete = [];
angular.forEach($scope.objects, function(cost) {
if (cost.selected == true) {
costsToDelete.push(cost);
}
});
$scope.deleted = true;
//need to put confirmation dialog here.
//URL: specific to timesheet deletion. it will be prefixed with constant url
var delRequestUrl = URLs.costsUrl + '/';
deleteService.deleteRecord($scope.objects, costsToDelete, delRequestUrl);
};
This is a service.
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
Alert('success');
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
Alert('error');
});
}
};
return deleteService; }])
I need a result like: Alert should display only once.
If all items are successfully deleted, then success or failure message.
Why dont you just create a boolean bit var status= false;//default value to true inside success callback handler and false inside error callback handler,
so once all calls are complete based on this bit you can alert success or failure
Angular JS Code:
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var statusBit = false; // status tracker
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
// Alert('success');
statusBit = true;
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
//Alert('error');
statusBit = false;
});
if(statusBit){
Alert('success'); //console.log('successfully deleted');
}
else {
Alert('error'); // console.log('error while deleting');
}
};
return deleteService; }])
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
var overallResult = true;
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
overallResult = false ;
});
}
};
return deleteService; }])
I am following tutsplus Real time web apps with Angularjs and Firebase.
I have main.js (below) which allows me to add and change items in Firebase in real time with no refresh of the browser (in Chrome and Safari).
However when I delete a message from Firebase I have to refresh the browser for the message list to update - so not in real time. I can't see where the problem is.
/*global Firebase*/
'use strict';
/**
* #ngdoc function
* #name firebaseProjectApp.controller:MainCtrl
* #description
* # MainCtrl
* Controller of the firebaseProjectApp
*/
angular.module('firebaseProjectApp')
.controller('MainCtrl', function ($scope, $timeout) {
var rootRef = new Firebase('https://popping-inferno-9738.firebaseio.com/');
var messagesRef = rootRef.child('messages');
$scope.currentUser=null;
$scope.currentText=null;
$scope.messages=[];
messagesRef.on('child_added', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
console.log(snapshotVal);
$scope.messages.push({
text: snapshotVal.text,
user: snapshotVal.user,
name: snapshot.key()
});
});
});
messagesRef.on('child_changed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
function deleteMessageByName(name){
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
$scope.messages.splice(i, 1);
break;
}
}
}
function findMessageByName(name){
var messageFound = null;
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
messageFound = currentMessage;
break;
}
}
return messageFound;
}
$scope.sendMessage = function(){
var newMessage = {
user: $scope.currentUser,
text: $scope.currentText
};
messagesRef.push(newMessage);
};
});
The code that is invoked when a message is deleted from Firebase:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
This code never actually deletes the message from the HTML/DOM.
There is a convenient deleteMessageByName method to handle the deletion. So if you modify the above to this, it'll work:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
deleteMessageByName(snapshot.key());
});
});