ng-file-upload stuck at progress - angularjs

Good night!.. I am a newbie working on MEAN Stack, and I'm trying to upload a picture using the ng-file-upload. This is the angular code:
app.controller('profilePicCtrl', ['Upload', '$scope', '$http',
function(Upload, $scope, $http){
$scope.watch(function(){
return $scope.file
}, function(){
$scope.upload($scope.file);
});
$scope.userID = localStorage.getItem('userID');
$scope.upload = function(file){
console.log("entro en upload");
if(file){
Upload.upload({
url:'api/profile/edit',
method:'POST',
data: {userId: $scope.userID},
file: file
}).progress(function(evt, status){
console.log("dale puej mijo ");
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status){
console.log('archivo subido');
}).error(function(error){
console.log(error);
})
}
};
}]);
Here is the express code:
module.exports.updatePhoto = function(req, res){
var file = req.file;
var userId = req.body.userId;
console.log("User "+userId+ " is submitting ", file.name);
}
And the last is the server-side code, where I call the controller:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var profileController = require('./routes/profile-controller');
...
app.post('api/profile/edit', multipartMiddleware, profileController.updatePhoto);
It doesn't go thru the controller, the server never responds. Thanks in advance for your attention.

I had a code that wasn't letting me go into any other method different than 'GET'. This one below was the guilty one:
if(req.method === "GET" || req.method === "POST"){
if(!req.isAuthenticated()) {
res.redirect('/#login');
}else{
return next();
}
}
Instead of the or sentence I had in the if just the req.method==='GET sentence, which was causing my code to go into an infinity loop returning the next() method but not finding one. Now with the or sentence my code goes to the POST methods.

Related

Angularjs files uploads says this request has no response data available

I used the code below to upload Image and username to server. it works fine.
Now I want to return the username and filename in a console but it says this request has no response data available. I have tried to use a successcallback() function but still with no luck. it seems the issue is from the successcallback(). can someone help me fix that.
file.upload = Upload.upload({
method: 'post',
url: 'image.php',
data: {username: $scope.username, file: file},
}).then(function successCallback(response) {
alert(response.data[0].username);
alert(response.data[0].file);
console.log(response.data[0].username);
});
below is the entire code
//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout','$http', function ($scope, Upload, $timeout, $http) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
url: 'upload.php',
data: {username: $scope.username, file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
console.log(response.data[0].username);
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
image.php
<?php
error_reporting(0);
$data = json_decode(file_get_contents("php://input"));
$username = strip_tags($data->username);
$return_arr[] = array("username"=>$username);
echo json_encode($return_arr);
exit();
The issue mentioned in the post above has been resolved.
I was sending the form parameter username as json_decode()
$data = json_decode(file_get_contents("php://input"));
$username = strip_tags($data->username);
Sending everything as post parameter solved my problem as in case below
$username = $_POST['username'];
Thanks

Controller not getting a response from factory

I'm trying to clean up my controller by doing http requests in services, but for some reason a functions in my controller is not getting a response from a service.
I have this function in my controller,
$scope.addMovie = function() {
addMovie.add().then(function(response){
if(response){
console.log ('Response')
} else {
console.log ('No reposone')
}
});
And this is the service,
(function(){
"use strict";
angular.module('addMovieseat')
.factory('addMovie',
function($http, $q){
return{
add: function(){
var deferred = $q.defer();
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
deferred.resolve(data.results);
console.log ('Succes getting data')
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
deferred.resolve(false);
});
$(".search_results").fadeOut(250);
return deferred.promise;
}
}
})
})();
When I run the $scope.addMovie function from the controller the console log shows a Succes getting data from the service and then a No response from the function in the controller. What's missing here?
//edit. I'm now trying to insert the data from the service into a scope in my controller,
$scope.addMovie = function() {
$scope.movieListID = {};
console.log ('empty' + $scope.movieListID)
movieAdd.add()
.then(function(response){
$scope.movieListID = response;
console.log ('Not empty' + $scope.movieListID)
})
.catch(function(response) {
console.log ('No search reposone')
});
}
but the console log displays a "undefined" message afther the "Response OK".
try to change this
$scope.addMovie = function() {
addMovie.add().then(function(response){
if(response){
console.log ('Response')
} else {
console.log ('No reposone')
}
});
to this:
$scope.addMovie = function() {
addMovie.add()
.then(function(response){
console.log ('Response OK');
})
.catch(function(responce){
console.log ('Response error');
});
like this you are actually catching any errors which may be happening in you factory/service...

Passing object from Node/Express Router to AngularJS Controller

I have the following:
Node/Express router:
var City = require('./models/city');
module.exports = function(app) {
app.get('/cities/:zip', function(req, res) {
console.log(req.params.zip);
var query = City.find({"zip" : req.params.zip})
query.exec(function(err, city) {
if (err)
res.send(err);
console.log(city);
res.json(city);
});
});
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
});
};
Angular Service:
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
var zip = zip.zip
return $http.get('/cities/' + zip);
}
}
}]);
Angular Controller:
angular.module('CityCtrl', []).controller('CityController', ['$scope', '$http', 'City', function($scope, $http, City){
$scope.update = function (zip) {
$scope.weather = City.get({zip : zip});
if(zip.length = 5){
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?zip='+ zip +',us&callback=JSON_CALLBACK').success(function(data){
$scope.data=data;
console.log(data.name);
});
}
}
}]);
Everything seems to be working fine. However, when I try to log the $scope.weather I get the entire header. I've tried logging $scope.weather.name (I know it's there) and then it returns "undefined". When I check what the server is logging it appears to log the correct JSON response. Any idea of how to get the "name" field of the returned document?
Replace $scope.weather = City.get({zip : zip}); to City.get({zip : zip}).then(function(response){$scope.weather= response.data});
As we know $http return a promise object so you must have to resolve it. you are not resolving it in service so you have to set $scope.weather in then.

How to make a service for a Signup form in Angular js

I am trying to understand how angular work in the client side when submitting forms. I halfway there but I get an error, and I can't move forward.
In my controller I have the following code:
$scope.SaveData = function (data) {
if ($scope.submitText == 'Save') {
$scope.submitted = true;
$scope.message = '';
if ($scope.isFormValid) {
$scope.submitText = 'Please Wait...';
$scope.User = data;
RegistrationService.SaveFormData(data).then(function (response) {
alert(response);
if (response == 'Success') {
//have to clear form here
ClearForm();
}
$scope.submitText = "Save";
});
}
else {
$scope.message = 'Please fill required fields value';
}
}
}
And then in my registration service I have the following :
.factory('RegistrationService', function ($http, $q, $location) {
//here $q is a angularjs service with help us to run asynchronous function and return result when processing done
var fac = {};
fac.SaveFormData = function (data) {
var defer = $q.defer();
$http({
url: '/api/Users',
method: 'POST',
data: d,
headers: { 'content-type': 'application/json' }
}).success(function (d) {
// Success callback
defer.resolve(d);
$locationu.url('/');
}).error(function (e) {
//Failed Callback
alert('Error!');
defer.reject(e);
});
return defer.promise;
}
return fac;
});
What does data:d represent ? How should I defined so I can process the form?
I have the data in the scope but when I call SaveFormData I encounter problem with data:d it says undefined and I can't understand why is that so? And what does that part of the code do?
Any reference tutorial and explanation is welcomed
Thats because d is not defined, "data: d" is where you set the JSON object Being passed to the server in the request, bind you fields with ng-model="formDara.fieldname" then pass formData to your saveFormData(formData) and change "data: d" to "data: data".

How to return a success or fail code from Node.js to Angularjs

I am building my website with Angularjs and I am testing it with Node js and express. So, I am able to send a json item with information from the contact page form. But, I do not know How to return a success or fail code from Node.js to Angularjs to redirect to a thank you page. Also, I need to know how to send the information to my email and save it to a db and how to add a token for the form. I know that I'm using the MEAN stack. I learn better watch.
Here is my Node js:
var express = require('express');
var app = express();
var formidable = require('formidable');
app.use(express.static(__dirname + '/public')); // navigate to where the app reside
app.get('/', function (request, response) {
response.redirect('Index.html');
});
app.post('/Contact', function (request, response) {
var frm = new formidable.IncomingForm();
frm.parse(request, function(err, formData){
var Name = formData.Name,
Email= formData.Email,
Message = formData.Message;
response.writeHead(200, { "Content-Type": "application/json" });
response.end("{'status:' 200}");
});
});
var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);
and here is my Angularjs:
$scope.submit = function () {
console.log('Im in the controller');
console.log($scope.formData);
$http({
method : 'POST',
url : '/Contact',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/json' }
}).success(function(result, status, headers, config) {
console.log(result);
if(result.status == "???"){
redirectTo: '/Thnkyu';
}
}).error(function(result, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(result);
});
}
When I submit the form; the console showed: TypeError: Cannot read property 'protocol' of undefined Before it showed: ERR_CONNECTION_REFUSED because I had the url portion before I setted the headers and data.
The problem was I use the angularJs $http dependence as shown above; but, it did not work. So, I use the $http dependence like so:
$scope.submit = function () {
console.log($scope.formData);
$http.post("/contact", $scope.formData)
.success(function(reponse){
if(reponse.status == 200)
console.log('im in')
$location.path('/thnkyu');
});
and the response from the server is like this:
...
if(!eor){
console.log(eor);
response.json({status: 200});
}

Resources