Sails.JS pass data from the view to the controller - javascript

in Sails.js, I am trying to pass the role/mentor key/value pair to be received by the contoller function '/select'
VIEW.ejs
...
$.post( '/select', {role: 'mentor'} );
...
CONTROLLER
select: function(req, res) {
var printRole = req.param('role');
return res.send("The role is: " + printRole);
}
So far the result I receive on the screen is : The role is Undefined
please help

I think param should be plural as in var printRole = req.params('role')

Related

Post method not working in this temp.js

Post method not working:
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.post('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end( JSON.stringify(data));
});
})
And I'm trying to access this by passing:
http://127.0.0.1:7000/addUser
Please help me through this.
The error is like this:
Cannot GET /addUser
The problem here is that you're trying to use the GET HTTP verb and not POST you could either:
Test this using a tool such as Postman (https://www.getpostman.com/) or use cURL to POST.
Change POST to GET and open it from within your browser.
Create a HTML Form element w/ the required fields and submit the form to the POST url.
Hope this helps.
A browser's URL bar will always make a GET request, not a POST. So you need to define your route as such :
app.get('/addUser', ....
instead of
app.post('/addUser', ....

express-handlebars # if statement

I am still pretty new to NodeJS and I am using the express and express-handlebar packages.
However, the 'if-statement' does not work properly, in fact not at all. I suppose the reason for this is that I do not use a template for the if-statement.
Using just the package 'handlebars', I would go with:
rs.readFile('files/test.hbs', 'utf-8', function(err, data)
{
var template = hbs.compile(data);
var result = template ({name: 'name', value1: 'value1', value2: 'value2'});
res.end (result);
...
}
This solution works actually.
However, I have already used express-handlebars in the entire code and would like to keep on using it. I got following code:
//I´ll receive value1 and value2 later either directly from my database or with the help of MQTT
var value1 = ' value1';
var value2 = 'value2';
var name = 'name';
var helpers={
value1:function(){return value1;},
value2:function(){return value2;},
name: function(){return name;}
}
router.get('/', function(req, res){
res.render('index', {helpers});
});
My html code looks like following:
<div>
<h1> {{value1}} </h1>
<h2> {{value2}} </h2>
{{#if name}}
<h3> hello there! </h3>
{{/if}}
</div>
value1 and value 2 are shown properly. 'hello there!' isn´t as I suppose it is not a template.
Does anyone know how I can make code work with express-handlebars?
I just answered it by myself.
The solution is:
router.get('/', function(req, res){
res.render('index', {
name,
helpers});
});
add this in server.js
const isEqual = function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
var hbs = require('hbs');
hbs.registerHelper('if_eq', isEqual);

How should I extract value from Url in Node Js

I recently started programming on nodeJs.
I am using Angular JS, resource to call API's as
demoApp.factory('class', function ($resource) {
return $resource('/class/:classId', { classId: '#_classId' }, {
update: { method: 'PUT' }
});
});
And in Controller, I have delete method as;
// The class object, e {classId: 1, className: "Pro"}
$scope.deleteClass = function (class) {
var deleteObj = new Class();
deleteObj.classId = class.classId;
deleteObj.$delete({classId : deleteObj.classId}, function() {
growl.success("Class deleted successfully.");
$location.path('/');
},function () {
growl.error("Error while deleting Class.");
}
);
};
Using browser, I verified call goes to :
http://localhost:3000/class/1
Now in node Js, How should I extract value from Url,
In server.js
app.use('/class', classController.getApi);
In classController.js
exports.getApi = function(req, resp){
switch(req.method) {
case 'DELETE':
if (req) {
// how to extract 1 from url.
}
else {
httpMsgs.show404(req, resp);
}
break;
I have tried ,
console.log(req.params);
console.log(req.query);
But no luck.
I am seeing
console.log(req._parsedUrl);
query: null,
pathname: '/class/1',
path: '/class/1',
Any help appreciated.
This should be a get call right ? You can use angular $http service, with method as get. Replace your app.use('/class') with app.get('/class', function). Then you can use req.param('classId') to retrieve data. I think it should work.
Try updating your app.use to app.use('/class/:classId'), then try req.params.classId
Try using req.hostname as in:
`http://host/path'
Check this answer.
Tldr;
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Also read the docs on node url.

AngularJS $resource 'GET' accesses the correct API, but 'PUT' and 'POST' do not

Follow up from AngularJS $resource calls the wrong API URL when using method:POST
My controller is set up like this, with Angular's $resource:
$scope.updateProduct = $resource('/api/updateProduct/:product/:param/:value',{},{
query: {method:'GET'},
post: {method:'POST'},
save: {method:'PUT', params: {brand: '#brand', param:'#param', value:'#value'}},
remove: {method:'DELETE'}
});
$scope.updateProduct.save({
product : $scope.post._id,
param: 'likes',
value: $scope.user._id
});
My server runs on NodeJS and ExpressJS. In my console, when the save operation is called, I can see:
POST /api/updateBrand/<productid>/likes/fun,%20quirky%20loud,%20boho,%20hippy 200 22ms - 2.31kb
However, my API is not being correctly accessed. For instance, if I go to the above URL in my browser, the API function is called, and my database is updated (and it is reported in my server's console). Yet when Angular does a PUT on this URL, nothing happens at all.
Interestingly, when I change $scope.updateProduct.save() to $scope.updateProduct.get(), the API is correctly called and everything works fine.
Any ideas what's going on here?
EDIT: Here's the server setup:
ExpressJS API setup:
app.get('/api/updateProduct/:product/:param/:value', api.updateProduct);
API code
exports.updateProduct = function (req, res) {
console.log("TEST")
var product = req.params.product;
var param = req.params.param;
var value = req.params.value;
var props = { $push: {} };
if(param == 'userTags'){
var oldVal = value;
value = oldVal.match(/[-'"\w]+/g);
props.$push[param];
props.$push[param] = {$each: []};
props.$push[param].$each = value;
}else{
var props = { $push: {} };
props.$push[param] = value;
}
db.products.update({"_id": ObjectId(product)}, props, function (err, record) {
if (err || !(record)) {
console.log("Lookup Error: " + err);
} else{
console.log("Updated " + product + " with " + param);
console.log(record);
res.json({obj:record})
}
});
};
It seems that your server is not waiting for a POST or PUT request, but a GET request as per your configuration.
app.get('/api/updateProduct/:product/:param/:value', api.updateProduct);
According to the ExpressJS API (http://expressjs.com/api.html), you should be able to replace the get with any valid http verb.
app.VERB(path, [callback...], callback)
app.post('/api/updateProduct/:product/:param/:value', api.updateProduct);
app.put('/api/updateProduct/:product/:param/:value', api.updateProduct);

Ember data doesn't append parameters to the query

Ember data just doesn't append parameters to the query. I have a tags route like this
example
App.TagsRoute = Ember.Route.extend({
model: function(params) {
var tag = params.tag_name;
var entries = this.store.find('entry', {tags: tag});
return entries;
}
});
but this keeps making the same request as this.store.find('entry').
i'm doing it wrong?
Edit:
My router looks like this:
App.Router.map(function(){
this.resource('entries', function(){
this.resource('entry', { path: '/entry/:entry_id/:entry_title' });
});
this.route('tags', { path: '/t/:tag_name' });
});
when i request (for example) localhost:8888/#/t/tag
the value of params.tag_name is 'tag'
edit2:
My REST adapter
App.ApplicationAdapter = DS.RESTAdapter.extend({
bulkCommit: false,
buildURL: function(record, suffix) {
var s = this._super(record, suffix);
return s + ".json";
},
findQuery: function(store, type, query) {
var url = this.buildURL(type.typeKey),
proc = 'GET',
obj = { data: query },
theFinalQuery = url + "?" + $.param(query);
console.log(url); // this is the base url
console.log(proc); // this is the procedure
console.log(obj); // an object sent down to attach to the ajax request
console.log(theFinalQuery); // what the query looks like
// use the default rest adapter implementation
return this._super(store, type, query);
}
});
edit3:
making some changes to my TagsRoute object i get the next output:
App.TagsRoute = Ember.Route.extend({
model: function(params) {
var tag = params.tag_name;
var query = {tags: tag};
console.log(query);
var entries = this.store.find('entry', query);
return entries;
}
});
console output when i request localhost:8888/#/t/tag
Object {tags: "tag"}
(host url) + api/v1/entries.json
GET
Object {data: Object}
(host url) + api/v1/entries.json?tags=tag
Class {type: function, query: Object, store: Class, isLoaded: true, meta: Object…}
Ember data is attaching GET parameters. i think my error maybe is the requested url, it should be something like this
(host url) + api/v1/tags/:tag_name.json
instead of
(host url) + api/v1/entries.json?tags=:tag_name
SOLUTION
the build of ember-data (ember-data 1.0.0-beta.3-16-g2205566) was broken. When i changed the script src to builds.emberjs.com.s3.amazonaws.com/canary/daily/20131018/ember-data.js everything worked perfectly.
the proper way to add GET parameters is:
var query = {param: value};
var array = this.store.find('model', query);
thanks for your help
You are doing everything correct, are you sure the request being sent back to the server doesn't contain the query?
The full query isn't created until JQuery makes the call.
Did you look at the network tab in chrome (or whatever browser you are using) to see what it's sending back.
Watch the console in the jsbin below, it shows what happens when you use find with an object (for querying):
App.MyAdapter = DS.RESTAdapter.extend({
findQuery: function(store, type, query) {
var url = this.buildURL(type.typeKey),
proc = 'GET',
obj = { data: query },
theFinalQuery = url + "?" + $.param(query);
console.log(url); // this is the base url
console.log(proc); // this is the procedure
console.log(obj); // an object sent down to attach to the ajax request
console.log(theFinalQuery); // what the query looks like
// use the default rest adapter implementation
return this._super(store, type, query);
},
});
http://emberjs.jsbin.com/AyaVakE/1/edit
Additional questions:
hitting: http://localhost:8888/#/t/tag fires the tags route, sending in 'tag' to the tag_name. Your model hook is correct. Where are you seeing that the request is the same?
Additionally, you mentioned store.find('entries) and store.find('entry'). I know they handle pluralization of most things, but you should make sure those end up being the same endpoint /api/entries.
The RESTAdapter sends your query object to the jQuery.ajax() method by tacking it onto the data property of the settings object. (See here for info on what is done with the settings object.)
It looks like maybe the tag name is not defined. Try to make sure that the tag_name parameter is properly coming from your route.

Categories

Resources