How to pass $scope variable data into node.js backend server file? - angularjs

I have json data in $scope variable and i want to use that $scope variable inside my backend app.js node file.
This is my backend file app.js:
app.post('/upload', upload.single('file'), function(req, res) {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('./uploads/' + req.file.filename);
var sheet_name_list = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
//var values = [];
console.log(data);
return res.status(200).send(data);
});
app.post('/api/uploadlast',api.addNewContact, function(req,res){
Contact.bulkCreate(excels).then(function(users) {
return res.status(200).send(users);
}).catch(Sequelize.ValidationError, function(err) {
return res.status(422).send(err.errors[0].message);
}).catch(function(err) {
return res.status(400).send(err.message);
});
})
This is my controller file:
$scope.uploadFile = function() {
var file = $scope.myFile;
var uploadUrl = "/upload";
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
.then(function(response) {
//$state.reload();
$scope.excels = response.data;
console.log("success!!");
})
.catch(function() {
console.log("error!!");
});
}
$scope.uploadLast = function() {
$http.post('/api/uploadlast').then(function(response) {
$state.reload();
});
}
})
I want to get $scope.excels data into my backend to bulkcreate into databases.

You can pass any data with a post request as the second parameter of $http.post(). So you can do something like:
$scope.uploadLast = function() {
var data = {
excels: $scope.excels
};
$http.post('/api/uploadlast', data).then(function(response) {
$state.reload();
});
}
And in your backend, you can access it like:
app.post('/api/uploadlast',api.addNewContact, function(req, res){
var data = req.body.excels;
Contact.bulkCreate(data).then(function(users) {
return res.status(200).send(users);
}).catch(Sequelize.ValidationError, function(err) {
return res.status(422).send(err.errors[0].message);
}).catch(function(err) {
return res.status(400).send(err.message);
});
});

Related

how to get function return value in a variable using angularjs

Here is my code of angularjs file
$scope.httpPost = function (url, json_form_data) {
$http.post(url, json_form_data)
.then(function (response) {
$scope.responseData = response.data;
return $scope.responseData;
}, function (response) {
$scope.content = "Something went wrong";
});
};
Here is the function in which i am calling the above function
$scope.getAuthToken = function (account_type, auth_type, email, type_of_request) { // type of request means login or signUp
var account_type = account_type;
var form_data = {
'email': email,
"auth_type": auth_type,
"account_type": account_type
};
$scope.responseData = $scope.httpPost($scope.authTokenUrl, form_data);
console.log("value of res");
console.log($scope.responseData);
};
The output of the above code is
value of res
loginAndSignup.js:138 undefined
My question is that How can i access that value which function returning because i needed that value.
I tried the following solution
$scope.httpPost = function (url, json_form_data) {
return $http.post(url, json_form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
};
$scope.login = function (email, auth_token, auth_type, account_type) {
var password = $scope.password;
var form_data = {
//form data
};
var url = $scope.loginUrl;
$scope.httpPost(url, form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
using $q (A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.)
click here for more detail
used this function
$scope.httpPost = function (url, json_form_data) {
var d = $q.defer();
$http.post(url, json_form_data)
.then(function (response) {
d.resolve(response);
}, function (response) {
d.reject(response);
});
return d.promise;
};

Angular FIle upload Custom headers for upload all

I want to add custom headers to a file before Uploading. Both methods below are not working:
$scope.uploadallman = function (qID) {
alert(qID);
uploader.headers = { QuestionID: qID };
//item.headers = {
// MyHeader: qID,
//};
uploader.uploadAll();
}
Maybe not the best solution, but it's the way I do it and it's working.
function _uploadFile(resourceURL, file) {
var deferred = $q.defer();
var config = {};
config.headers = {};
config.transformRequest = angular.identity;
config.headers['Content-Type'] = undefined;
// config.headers['MyCustomHeaderKey'] = MyCustomHeaderValue; // Optional
var formData = new FormData();
formData.append('file', file);
// formData.append('myCustomFormDataAttributeKey', myCustomFormDataAttributeValue); // Optional
$http.post(resourceURL, formData, config)
.success(function (response) {
deferred.resolve(response);
})
.error(function (err, status) {
deferred.reject(err);
});
return deferred.promise;
}
This is very good topic about the file upload in Angular:
How to POST JSON and a file to web service with Angular?

error in web api controller when getting value send from js

i am new in angularjs i have a project where some get and post method
this is my js
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope, $http) {
$scope.joblist = function (Data) {
$scope.job = [];
$.ajax({
url: "/JobApi/getjoblist",
dataType: 'jsonp',
method: 'GET',
data: Data,
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.$apply(function () {
debugger;
if (response != null) {
$scope.divstateList = false;
$scope.divjobList = true;
$scope.job = response;
}
});
})
.error(function (error) {
alert(error);
});
}
});
And this is my web api controller
[System.Web.Http.Route("JobApi/getjoblist")]
[System.Web.Mvc.HttpPost]
public List<Getjoblist> getjoblist([FromBody]string Data)
{
try
{
JobBL objbl = new JobBL();
var joblist = objbl.Citywisejoblist(Convert.ToInt32(Data));
List<Getjoblist> list = new List<Getjoblist>();
foreach (var t in joblist)
{
Getjoblist GetAll = new Getjoblist();
GetAll.jobID = Convert.ToInt32(t.ID);
GetAll.jobtital = t.Title;
GetAll.jobdescription = t.Description;
GetAll.jobimage = t.JobImage;
list.Add(GetAll);
}
return list;
}
catch (Exception ex)
{
throw ex;
}
}
not getting the value in controller send from js how to solve the problem please help me

PUT request to Amazon S3 bucket using presigned url returns 403

I'm getting the presigned url from a Node.js server using aws-sdk. Here is the server code, which always returns a 200 code and a the url:
getSignedUrl: function(req, res, next){
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var s3_params = {
Bucket: S3_BUCKET,
Key: req.query.file_name,
ContentType: req.query.file_type,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if (err) {
return next(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+req.query.file_name
};
res.json(return_data);
}
});
}
My client-side is Angular. I've uloaded a file using a File Reader service:
.factory('fileReaderFactory', ['$q', '$log', function($q, $log){
....
var getReader = function(deferred, scope) {
var reader = new FileReader();
....
return reader;
};
var readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
scope.$broadcast("fileData", {
name: file.name,
type: file.type
});
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
}]);
My controller:
.controller('UploadCtrl', ['apiFactory','fileReaderFactory','$scope', function(apiFactory, fileReaderFactory, $scope){
$scope.data = {};
$scope.fileData = {};
...
$scope.readFile = function() {
fileReaderFactory.readAsDataUrl($scope.file, $scope)
.then(function(result){
$scope.imgSrc = result;
imgUploaded = true;
});
};
$scope.upload = function(){
apiFactory.getSignedUrl($scope.fileData)
.then(function(result){
return apiFactory.uploadS3(result, $scope.fileData, $scope.imgSrc);
})
.then(function(result){
}, function(error){
console.log(error);
})
};
....
}]);
And finally the snippets of code from the apiFactory:
apiFactory.getSignedUrl = function(data){
return $http({
method: 'GET',
url: API_URL + '/sign_s3',
params : {
"file_name": data.name,
"file_type": data.type,
}
});
};
apiFactory.uploadS3 = function(result, data, file){
return $http({
method: 'PUT',
url: result.data.signed_request,
data: file,
headers: {
"x-amz-acl": "public-read"
}
});
}
I always get a 403: Forbidden back from Amazon when I try to upload the file using the signed url, however.

Why does my angular/express GET work but not POST?

Here how my button's set up. The Updates.getUpdates is working. Updates.postAnUpdate returns 404
$scope.postUpdate = function () {
console.log($scope.update);
Updates.postAnUpdate($scope.update);
Updates.getUpdates().then(function (data) {
$scope.updates = data;
});
};
Here is my lovely services
app.factory('Updates', ['$http',
function ($http) {
return {
//Get the current users messages
getUpdates: function () {
return $http({
url: '/updates/',
method: 'get'
}).then(function (result) {
return result.data;
});
},
postAnUpdate: function (update) {
return $http({
url: '/updates/post',
method: 'post',
data: {
update:update,
}
}).then(function (result) {
return result.data;
});
}
};
}]);
Here's my routes to handle the urls
var updates = require('./routes/updates.js');
//Project Updates
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
And finally, here's the code that works with a 200 and console text.
exports.getAll = function (req, res) {
console.log('It worked');
}
So everything should be working for the post too, but it isn't. I'm just trying to do a console command so I know it works and I'm getting a 404
exports.newPost = function (req, res) {
var db = mongo.db,
BSON = mongo.BSON,
newPost = {};
console.log('This is giving me 404 instead of showing up in terminal');
newPost.content = req.body.update;
newPost.author = req.user._id;
newPost.date = new Date();
db.collection('updates').save(newPost, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
}
Looks as though this is a simple typographic error. in your routes:
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
I think you want
app.post('/updates/post', updates.newPost);

Resources