I am trying to pass a variable from the controller to my DAO service in an Angularjs application (frontend) and nodejs backend.
here is my controller :
$scope.afficherProfils = function() {
$http.get(configuration.URL_REQUEST + '/profile')
.success(function(data) {
$scope.owner = data._id;
console.log('$scope.owner =========>');
console.log($scope.owner);
$http.get(configuration.URL_REQUEST + '/listerProfil', {
owner: $scope.owner
})
.success(function(data) {
console.log('$scope.listeProfils =========>');
console.log(data);
$scope.listeProfils = data;
});
});
};
i am calling /profile to get the _id of the account that has added the profile, after that i call /listerProfil inside success and pass the owner parameter.
and in my DAO service the code is the following :
exports.all = function(req, res) {
console.log('req.body ================================>');
console.log(req.body);
Profil.find({
owner: req.body.owner
}, function(err, profils) {
if (err) {
res.send({
'result': 'error'
});
} else {
res.send(profils);
}
});
};
and i don't know why my req.body is empty when i do a console.log
any ideas ?
HTTP-CRUD(Create-$http.post,Read-$http.get,Update-$http.put,Dlete-$http.delet)
$http.get-It used to get the value means this body contain empty value
$http.post-It used to create value means this body contain data (your are post some data to server)
$http.update-It used to update exit value this body also contain data
$http.delete-It used to delete exit value this body contain empty(send through param(?id=1111))
so change your code http.get to http.post
Related
Hellow all,
I'm Newbie to Nodejs and Firebase, I need two functionalities to takes place in a single function and also I have written a piece of code it's works fine.
But My question is, the code I have written is the correct way to achieve the multiple functionality or do we have any other alternate method(correct way) to achieve the same functionality.
Doubt :
Retrieving relevant details of project ----> Inside Callback function ----> saving data to another table ----> Inside Callback function ----> Deleting data from table -----> Inside Callback function ----> response
Do we need to write the functionality inside the nested callback function to achieve the output or is there is any other way to achieve it .
// Nodejs Post Function
app.post('/delete_user_request_project/', function (req, res)
{
if (!is_admin_login(req.cookies.login_type))
{
return res.redirect('/');
}
var project_id = req.body.project_id; // Getting the project Id
let del_ref = admin.database().ref("user_request_project/" + project_id); // Targeting the details of the project to fetch that particular data
del_ref.once("value", function (snapshot)
{
var request_project_obj = snapshot.val(); // fetching the details of project
if (request_project_obj != null)
{
let update_ref = admin.database().ref("deleted_user_request_project/" + project_id);
update_ref.set(
request_project_obj // Updating project details to another table
).then(function ()
{
del_ref.remove().then(function () // Deleting the details from project Table
{
return res.status(200).send('success');
});
});
}
else
{
var error = "プロジェクトが存在しない";
req.flash("error", error_message);
return res.send({
status: 'error',
error: error
});
}
});
})
TIA
I would suggest you use the Promise version of the once() method instead of the Callback version, as follows. It will allow you to correctly chain the different promises returned by the asynchronous Firebase method.
app.post('/delete_user_request_project/', function (req, res) {
if (!is_admin_login(req.cookies.login_type)) {
return res.redirect('/');
}
var project_id = req.body.project_id; // Getting the project Id
let del_ref = admin.database().ref("user_request_project/" + project_id); // Targeting the details of the project to fetch that particular data
del_ref.once("value")
.then(function (snapshot) {
var request_project_obj = snapshot.val(); // fetching the details of project
if (request_project_obj != null) {
let update_ref = admin.database().ref("deleted_user_request_project/" + project_id);
return update_ref.set(request_project_obj); // Updating project details to another table
}
else {
throw new Error('request_project_obj null');
}
})
.then(function () {
return del_ref.remove();
})
.then(function () // Deleting the details from project Table
{
return res.status(200).send('success');
})
.catch(function (error) {
if (error.message === 'request_project_obj null') {
var error = "プロジェクトが存在しない";
req.flash("error", error_message);
return res.send({
status: 'error',
error: error
});
} else {
//...
}
})
})
I have a NODE.JS api using expressjs that connects to an SQL Server, and I want to use it in an angular project. I make use two files, a route file and a controllers file. My route file is as follows:
module.exports = (app) => {
const UsrContrllr = require('../Controllers/users.controllers');
//1. GET ALL USERS
app.get('/api/users', UsrContrllr.func1);
//2. POST NEW USER
app.post('/api/user/new', UsrContrllr.func2);
};
And my controllers file is given below:
const mssql = require('mssql');
exports.func1 = (req, res) =>
{
// Validate request
console.log(`Fetching RESPONSE`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `SELECT * FROM USERS`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() === '') {
res.send('Oops!!! Required data not found...');
}
else {
// send records as a response
res.send(recordset);
}
};
});
};
exports.func2 = (req, res) =>
{
// Validate request
console.log(`INSERTING RECORD ${req}`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `INSERT INTO GDUSERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() == '') {
res.send('Oops!!! Required data not found...');
}
else {
// Send records as response
res.send(recordset);
}
};
});
};
The GET request works well, but when I try to run the POST request directly from the angular application, I get an error stating
Cannot GET URL/api/user/new
The angular code in my angular project is:
signup() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(this.user); //User details come from a form
this.http.post(“URL", this.user, options)
.subscribe(
(err) => {
if(err) console.log(err);
console.log("Success");
});
}
I’m not sure whether the angular code I’m using, is right or not, and I don’t know where I’m going wrong. How does one exactly send a http POST request from an Angular project?
this i the way i handled my user signup with http.post calls. my approach is slightly different when signing up user because i am using a promise instead of observable (which i normally use for my servicecalls). but i will show you both ways.
createUser(user: User): Promise < string > {
const promise = new Promise < string > ((resolve, reject) => {
const userForPost = this.createUserForPost(user);
this.http.post(environment.backendUrl + '/api/user/signup', userForPost, this.config).toPromise < HttpConfig > ()
.then(createdUser => {
}).catch(error => {
console.log(error);
});
});
return promise;
}
here another example with an observable
createForumPost(forumPost: ForumPost) {
this.http.post < { message: string, forumPostId: string } > (environment.backendUrl + '/api/forumPosts', forumPost).subscribe((responseData) => {
const id = responseData.forumPostId;
forumPost.id = id;
});
}
i defined my URL somewhere else and then just use the environment.backedUrl + 'path' to define my path (the same as the path in your backend controller)
this is one of my first answers here on SO. i am sry if it is a bit messy
i hope i was able to help with my examples :)
I'm making a website where i need an id passed to an express route.
I have a button (id='approve_appln') which fetches a route. The javascript involved is as follows:
var appr_appln = document.getElementById('approve_appln');
appr_appln.addEventListener('click', function(e) {
var approve_id = appr_appln.getAttribute('data');
fetch('/approved', {method: 'POST'})
.then(function(response) {
if(response.ok) {
alert(approve_id);
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
alert('error');
});
});
I need to pass the approve_id variable to the /approved route. The route is now empty though:
app.post('/approved',function(req,res){
});
How do I pass the approve_id variable so it can be used to refer a particular object in my database?
Your endpoint can have an id attached to it
for example:
app.post('/approved',function(req,res){
});
should be
app.post('/approved/:id',function(req,res){
const id = req.params.id // This is how you access URL variable
});
Keep in mind :id here is a variable that can be replaced by an actual ID when requesting from URL.
for example you can do something like this ```http://localhost/approved/1231451324123
so to follow your example, you can just send the ID with the URL by doing something like this
var appr_appln = document.getElementById('approve_appln');
appr_appln.addEventListener('click', function(e) {
var approve_id = appr_appln.getAttribute('data');
fetch(`/approved/${approve_id}`, {method: 'POST'})
.then(function(response) {
if(response.ok) {
alert(approve_id);
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
alert('error');
});
});
note I only changed this line fetch('/approved', {method: 'POST'})
I replaced single quotes ' with ` so I can concatenate easier. also ${} means I can add any CODE inside these brackets.
Good luck, if you need more explanation let me know.
How can the variables set using apigee-access be used in express?
I am trying to get a variable using apigee-access like this:
http.createServer(function(req, resp) {
var userId= apigee.getVariable(req,username);
resp.end('Hello, World!\n'+userId+' Error:'+err);
});
and the trying to use the variable userId in
app.post('/employees', function(req, res) {
if (!req.is('json')) {
res.jsonp(400, {
error : 'Bad request'
});
return;
}
var b = req.body;
var e = {
'userName' : userId,
'displayName' : userId+"_details",
'phone' : b.phone
};
createEmployee(e, req, res);
});
I am getting an error ReferenceError: "userId" is not defined. while executing the same . Is there a way to access this variable?
You've defined userId as a local variable in the scope of the createServer function. By the time the server callback is fired and userId is defined, your e setter code has already been executed.
I imagine it works in the resp.end though right? It writes it to the page? You'll need to devise a more "node-like" way of handling the userId that doesn't require storing the userId as a global variable (that would be VERY bad) or even storing it in code at all. I'd recommend using a route path and require the end user to specify the userId when making a POST:
app.post('/employees/:userId', function(req, res) {
// req.params.userId can now be used
if (!req.is('json')) {
res.jsonp(400, {
error: 'Bad request'
});
return;
}
var body = {
userName: req.params.userId,
displayName: req.params.userId+"_details",
phone: req.body.phone
};
// now you're probably going to do something with 'body'
});
Is it possible to reuse / call the blueprint function (find/create/update/destory) and just add some items needed for the controllers. I'm sorry if I'm having hard time expressing my question but hopefully my example will help.
Example:
modue.exports = function(){
index: ....,
create: function(req, res){
try{
// i want to call the blueprint here to save some things
create(req, res);
// then do more after creating the record
....
}catch(err){
// want to catch some error here like validation err
// instead of sending it to res.serverErr();
}
}
....
}
//File api/controller/UserController.js
// suppose the model is User under api/models
modue.exports = {
create: function(req,res){
// pass req.query to User Model's Create function, so you dont need to rewrite all
//optional paramters for this overwrite version
User.create(req.query).exec(function(e, r){
if(e){
// !!!try to create in a different way!
}
})
}
}
You need to first copy blueprint folder from sails which is present in node_modules folder
Paste the blueprint folder in you api folder
Then in your controller for e.g UserController include actionUtil for e.g
var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');
module.exports = {
create: function (req, res) {
// paste code from blueprint create.js file
var Model = actionUtil.parseModel(req);
// Create data object (monolithic combination of all parameters)
// Omit the blacklisted params (like JSONP callback param, etc.)
var data = actionUtil.parseValues(req);
// Create new instance of model using data from params
Model.create(data).exec(function created(err, newInstance) {
// Differentiate between waterline-originated validation errors
// and serious underlying issues. Respond with badRequest if a
// validation error is encountered, w/ validation info.
if (err)
return res.serverError({status:500, message:'error', err: err});
// If we have the pubsub hook, use the model class's publish method
// to notify all subscribers about the created item
if (req._sails.hooks.pubsub) {
if (req.isSocket) {
Model.subscribe(req, newInstance);
Model.introduce(newInstance);
}
// Make sure data is JSON-serializable before publishing
var publishData = _.isArray(newInstance) ?
_.map(newInstance, function (instance) {
return instance.toJSON();
}) :
newInstance.toJSON();
Model.publishCreate(publishData, !req.options.mirror && req);
}
// do your after create stuff here
// Send JSONP-friendly response if it's supported
res.ok({status: 200, message: 'ok', results: newInstance});
});
}
}