Passing value angular to the node - angularjs

I'm trying to pass the form values but I'm not getting it, I've tried it in several ways.
Apparently Node.js is not recognizing the parameters passed to the url, I have no idea what it might be.
//AngularController
$scope.adicionarUsuario = function () {
$http.post("/usuario/salvar",{params:{"usuario":$scope.usuarioform}})
.success(function (data) {
delete $scope.usuarioform;
alert(data);
$scope.salvo = true;
$scope.cadastraUsuario.$setPristine();
}).error(function (data) {
$scope.erro = true;
$scope.message = "Aconteceu um problema: " + data;
});
};
//Node Server
app.post("/usuario/salvar",function (req, res){
usuario = req.params.usuario;
if(usuario.nome == null){
console.error("Ocorreu algum problema");
res.status(500).send('Acontenceu algum problema!');
}else{
MongoClient.connect(url, function (err, db) {
if (err){
console.error(err.stack);
res.status(500).send('Acontenceu algum problema!');
}else {
var collection = db.collection('usuarios');
//Salvar Usuario
var salva_usu = {nome: usuario.nome, email: usuario.email, senha: usuario.senha};
collection.insert(salva_usu, function (err, result) {
if (err){
console.error("Ocorreu algum problema");
res.status(500).send('Acontenceu algum problema!');
}else res.status(200).send("Salvo!");
});
//Fecha a conexão
db.close();
}
});
}
})

It's more common to send parameters using data in a POST, especially yours is an object rather than strings.
You can try modifying your code to use data, or send the 3 strings you need in 3 different params.
Personally I prefer the first way because your data contains a password, which doesn't look nice if it is appended in the request URL.

The request's data is available under the data attribute.
Also, it's most likely just going to be a JSON literal -- that is, a JS String. Parse it with JSON.parse()!
Simply replace:
app.post("/usuario/salvar",function (req, res) {
usuario = req.params.usuario;
// ...
By:
app.post("/usuario/salvar",function (req, res) {
usuario = JSON.parse(req.data).params.usuario;

Related

throw new ERR_INVALID_ARG_TYPE('chunk',['string','Buffer'],chunk);TypeError[ERR_INVALID_ARG_TYPE]:The "chunk" arg must be type string or Buffer

I am trying to get the contents of a .json file using a node js service into an angularjs method. But am getting following error:
_http_outgoing.js:700
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at ServerResponse.end (_http_outgoing.js:700:13)
here are the corresponding code fragments...
angular controller: the commented lines are all of those which i have tried and failed with.
var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
process: currentProcess,
date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
if (response != undefined) {
// var r = JSON.parse(response);
//$scope.storestats.push(r);
//$scope.storestats.push(r);
//var r = JSON.parse(response);
$scope.storestats.push(response);
//angular.forEach(r, function(value, key) {
// $scope.storestats.push({key : value});
//});
}
});
NODEJs service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.end(msgs1);
});
}
catch (err) {
res.end(err.toString());
}});
P.S: The commented out lines are those which i have tried out with and failed. Also, the commented lines in the node service code snippet, give no error, and when logged show it correctly, but the data when in response of the controllers is blank.
I'm guessing a bit here, but I think you just need to change res.end() to res.send() in your Node code. The "end" method is used when you are streaming chunks of data and then you call end() when you're all done. The "send" method is for sending a response in one go and letting Node handle the streaming.
Also, be sure you are sending a string back!
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.send(msgs2); // NOTE THE CHANGE to `msg2` (the string version)
});
}
catch (err) {
res.send(err.toString()); // NOTE THE CHANGE
}
});
I had a similar error. It was because I was passing process.pid to res.end(). It worked when I changed process.pid to string
res.end(process.pid.toString());
Figured it out. 2 small changes were needed.. One in the controller, which was to use a "$resource.query" instead of "$resource.get". And in the service, as #jakarella said, had to use the stringified part in the .end();
Controller:
var resAss = $resource('/procs/getstorestats');
var stats = resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
stats.$promise.then(function (response) {
$scope.storestats.push(response);
}
Node Service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
var msgs2 = JSON.stringify(msgs1);
console.log(msgs2);
res.end(msgs2);
});
}
If you are using 'request-promise' library set the json
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
})
.catch(function (err) {
});
Thank you user6184932, it work
try {
await insertNewDocument(fileNameDB, taskId);
res.end(process.pid.toString());
} catch (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
in mysql2 the reason for the error is the sql word , sql is a query :
const sql = select * from tableName
pool.executeQuery({
sql,
name: 'Error list for given SRC ID',
values: [],
errorMsg: 'Error occurred on fetching '
})
.then(data => {
res.status(200).json({ data })
})
.catch(err => {
console.log('\n \n == db , icorp fetching erro ====> : ', err.message, '\n \n')
})
I got the error using Node v12 (12.14.1).
Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
Sample code for context.
const { Readable } = require('stream')
Readable.from(Buffer.from(base64content, 'base64'))
.pipe( ... )
Solution (for my case), was upgrading to Node v14 (14.17.3). e.g.
nvm use 14
nvm

How to Run an API Calls in Parallel (Node.js)

I am trying to run some API calls in parallel, but am having problems since I am trying to call a function again before the API data has been returned.
I am thinking that I could possibly use the new command in Node, but am not sure how to structure it into this scheme. I am trying to avoid recursion, as I already have a recursive version working and it is slow.
Currently I am trying to this code on the server.
loopThroughArray(req, res) {
for(let i=0; i<req.map.length; i++) {
stack[i] = (callback) => {
let data = getApi(req, res, req.map[i], callback)
}
}
async.parallel(stack, (result) => {
res.json(result)
})
}
....
function getApi(req, res, num, cb) {
request({
url: 'https://example.com/api/' + num
},
(error, response, body) => {
if(error) {
// Log error
} else {
let i = {
name: JSON.parse(body)['name'],
age: '100'
}
console.log(body) // Returns empty value array.length > 1 (req.map[i])
cb(i)
}
})
Is there a way to spawn new instances of the function each time it's called and accumulate the results to send back as one result to the client?
Here's an example of calling Web APIs (each with different parameters), using the Async library, we start by creating an array of N function variables.
const async = require('async');
const request = require('request');
//Set whatever request options you like, see: https://github.com/request/request#requestoptions-callback
var requestArray = [
{url: 'https://httpbin.org/get'},
{url: 'https://httpbin.org/ip'}
];
let getApi = function (opt, callback) {
request(opt, (err, response, body) => {
callback(err, JSON.parse(body));
});
};
const functionArray = requestArray.map((opt) => {
return (callback) => getApi(opt, callback);
});
async.parallel(
functionArray, (err, results) => {
if (err) {
console.error('Error: ', err);
} else {
console.log('Results: ', results.length, results);
}
});
You can easily switch the Url and Query values to match whatever you need. I'm using HttpBin here, since it's good for illustrative purposes.

array schema store empty values

I want store values in mongodb using node controller but it will store an empty array inside mongodb
1).This is node controller using to accept the req parameter
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'child.quiz.questionId' : req.params.questionId,
'child.quiz.score' : req.params.score,
//'child.quiz.time' : req.params.time
'child.quiz.time' : new Date().toISOString()
};
var childupdate = new childQuiz(userObj);
childupdate.save(function(err,data){
if(err) return next(err);
console.log("Data saved successfully");
res.send(data);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}
2).This is mongodb schema using to store the value. Here i am using array quiz schema to store values is array
child:{
quiz:[
{
/*questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'commonquestions'
},*/
questionId:{type:String},
score:{type:Number},
time:{type:String}
}
]
}
3).This is my json result sending values using postman
{
"__v": 0,
"_id": "57a43ec68d90b13a7b84c58f",
"child": {
"quiz": []
}
}
MongoDB save() function accepts 2 parameters, document and data, but in your code, you use a callback function. Should you check it out?
https://docs.mongodb.com/manual/reference/method/db.collection.save/#db.collection.save
Try with this code in your controller
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'questionId' : req.params.questionId,
'score' : req.params.score,
//'time' : req.params.time
'time' : new Date().toISOString()
};
var childupdate = new childQuiz();
childupdate.quiz.push(userObj);
childupdate.save(function(err){
if(err) return next(err);
console.log("Data saved successfully");
res.send(childupdate);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}

using tedious connection,need to get the total data

hai I am new to tedious and Es-6,It may be a silly question but I am struggling,
I want the total data in a array, using tedious connections here is my code:
getZipData() {
var Connection = require('tedious').Connection;
Request = require('tedious').Request;
var config = {
userName: 'xx',
password: 'xxxx',
server: 'xxx', // You can use 'localhost\\instance' to connect to named instance
options: {
database: 'xxxxx',
rowCollectionOnDone:'true'
}
}
var connection = new Connection(config);
var jsonArray = [];
connection.on('connect', function (err) {
if (err) {
console.log(err)
}
var sql = "SELECT * FROM xxxxx";
return new Promise(function(resolve,reject){
var request = new Request(sql,
(err, rowCount, rows)=>{
if (err) {
reject(err);
}
else {
alert("rows");
console.log(rowCount + 'rows');
}
});
request.on('row', (columns)=>{
var rowObject = {};
columns.forEach((column)=> {
rowObject[column.metadata.colName] = column.value;
});
jsonArray.push(rowObject);
});
connection.execSql(request);
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
alert("jsonArray2:"+jsonArray);
resolve(jsonArray)
});
});
})
}
componentWillMount() {
this.getZipData().then(function(resolved){
console.log(resolved);
alert("data:"+resolved);
}).catch(function(rejected){
console.log(rejected);
})
}
when i add the request.on('done', function(rowCount, more) also i didn't get any data can any one give the solution for it,
I want the total data to be displayed
It looks like you're calling resolve before your query has been executed:
var jsonArray = [];
// Register callback for row event
request.on('row', (columns)=>{
var rowObject = {};
columns.forEach((column)=> {
rowObject[column.metadata.colName] = column.value;
});
jsonArray.push(rowObject);
});
// Call resolve before executing request
resolve(jsonArray);
connection.execSql(request);
The docs mention a done event that indicates a request has completed:
request.on('done', function (rowCount, more, rows) {
// Call resolve here instead?
resolve(jsonArray);
});
Disclaimer: I've haven't actually used Tedious, but from the docs linked this looks like what you're looking for.

Can't push to array using mongoose

I have code, basically still the MEANJS boilerplate, and I added a section to the articles for commenting. My strategy for the comments was to expose a route in express, /comments/:commentId, with a very simple comment model (it has a user object, a content string, and a likes number). I extended the article model to include an array of object IDs for the comments, and when an article was loaded, my angular resources would make a call to the /comments/:commentId to retrieve the list of comments specified by the array. Following is my server code
/* below is comments.server.controller.js */
/* THIS IS NEVER GETTING CALLED */
exports.updateArticleComments = function(req, res){
Article.findById(req.comment.article).populate('user', 'displayName').exec(function(err, article){
console.log(article);
if (err) return res.json(err);
if (!article) res.json({err: 'oops!'}); //handle this ish
article.comments[article.comments.length] = req.comment._id;
article.save(function(err, article){
if (err){
console.log('error');
} else {
res.json(article);
}
});
});
};
exports.commentsByID = function(req, res, next, id) {
Comment.findById(id).populate('user', 'displayName').exec(function(err, comment) {
if (err) return next(err);
if (!comment) return next(new Error('Failed to load comment ' + id));
req.comment = comment;
next();
});
};
/* end comments.server.controller.js */
/* begin articles.server.routes.js */
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users.server.controller'),
articles = require('../../app/controllers/articles.server.controller'),
comments = require('../../app/controllers/comments.server.controller');
module.exports = function(app) {
// Article Routes
app.route('/articles')
.get(articles.list)
.post(users.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.read)
.put(users.requiresLogin, articles.hasAuthorization, articles.update)
.post(comments.createComment, comments.updateArticleComments)
.delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
// Finish by binding the article middleware
app.param('articleId', articles.articleByID);
};
/* end articles.server.routes.js */
Everything, and I mean everything, works, EXCEPT exports.updateArticleComments function. I have seriously written about 5 different function, trying lodash's _extend, and many other techniques. I can't figure out why the comments array is never being filled. Does anyone have any suggestions at all?
EDIT: was requested to share createComment, so here it is
exports.createComment = function(req, res, next){
var comment = new Comment({content: req.body.content, article: req.body.articleId});
comment.user = req.user;
comment.save(function(comment, err){
if (err){
return res.jsonp(err);
} else {
req.comment = comment;
next();
}
});
};
Article.update({_id: 'VAL' }, {
$push: {
'comments' : req.comment._id }},{upsert:true},
function(err, data) { });
Have you tried the push method? I'd also be curious if the value of comment _id is coming back and not undefined.

Resources