MEAN App - Can't use query in my find request - javascript

I'm currently having a hard time on using queries within my MEAN App.
In Detail, I'm trying to get the data matching to the input in a search field:
$scope.searchInput = function(search){
$http({
method: 'GET',
url: '/search',
params: {'licensor.name' : search}
})
.success(
function(success){
console.log(success)
})
.error(
function(error){
console.log(error)
});
}
On the server side my code looks like this:
app.get('/search', function(req,res){
ImportCollection.find(function(err, imports){
if(err) throw err
res.json(imports)
});
});
This allways returns the full collection.
Any ideas?

please pass your query with find function, your request will have some query parameter if you are passing the parameter.
for example -
app.get('/search', function(req,res){
ImportCollection.find(req.query).exce(function(err, imports){
if(err) throw err
res.json(imports)
});
});
Thanks

Related

How to use AngularJS $http to fetch data returned by an ExpressJS endpoint?

I have an ExpressJS route as below:
var exec = require('child_process').exec;
app.get('/someURL', function (req, res) {
exec('cp file1 file2', (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
// the *entire* stdout and stderr (buffered)
console.log('stdout: ' + stdout);
console.log(stderr);
});
return stdout;
})
This is basically to run a CLI command when the user goes to the specified route on the web app.
In my AngularJS controller I have the following function:
function getData() {
let deferred = this.$q.defer();
this.$http({
method: 'GET',
url: '/someURL'
}).then((response) => {
deferred.resolve(response);
}, (error) => {
deferred.reject(error);
});
return deferred.promise;
}
this.getData().then(function(response) {
console.log(response);
}).catch(function(err) {
console.log(err, err.stack);
});
When I run the application, I am getting the html code as the response at console.log(response), instead of stdout. How do I correct that?
app.get('/someURL', function (req, res) {
// Here do the processing that you need to do
res.send('response');
})
In your expressJS server, you are intercepting the request but you are not sending anything back. You have to specifically send something back using the 'res' object from the funtion parameter. You can add http status codes too like
res.status('200').send(data);

sending params through routes

I'm trying to pass some parameters through the URL, i tried to do it this way but it isn't working, the "get(\users:id)" is probably the mistake but i'm not sure whats the correct way:
$.ajax({
type: 'GET',
URL: "'../users/"+id+"'",
success: function(data) {
console.log("success");
}
})
and then i use this route:
app.get('/users/:id', function(req, res) {});
shouldn't this work?
Try this way:
$.ajax({
type: 'GET', URL: "'../users/"+id+"'",
success: function(data) {
console.log("success");
}
}):
An then the route should be:
app.get("/users/:id", function (req, res) {
var id = req.params.id;
});
Your problem seems to be attempting to hit a file system relative path from your client, and the fact that there is no response being sent from your endpoint. Try this (using fetch which is the newer way instead of $.ajax):
fetch('/users/' + id)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
And in your server:
app.get('/users/:id', function(req, res) {
console.log(req.params); // this should be an object containing an `id` param
res.send({});
});

Check if user's email exists in db

I have a basic login form and want to authenticate whether a user's email exists in the db, but am not sure of the syntax for angular + node.
Main.js I have a ng-click on the submit button which runs this function. I get the email from the input and somehow need to pass this on to check the db?
$scope.logIn = function() {
var email = $scope.formInfo.email;
$http.get('/findUser').success(function(response){
console.log('find user data');
console.log(response);
});
};
Server.js I have the connection to the db but am unsure of how to make the connection with the client and backend data or what the syntax is
app.get('/findUser', function(req, res){
//what do I do here?
db.rejoin_your_ex.find({ email: 'the user's email' }, function(err, docs){
res.json(docs);
});
});
Client Side
$scope.logIn = function() {
var email = $scope.formInfo.email;
$http({
url: '/findUser',
method: "GET",
params: {"email": email}
}).success(function(response){
console.log('find user data');
console.log(response);
});
};
Server Side
At backend, you can use Mongoskin module for mongodb specific queries.
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/test");
db.bind('user');
app.get('/findUser', function(req, res){
//what do I do here?
db.user.find({ email: req.params.email }, function(err, user){
res.json(user);
});
});
Hope it helps you.

ExpressJS - res.redirect after DELETE request

I have been searching all over for how to do this - I am trying to redirect after a DELETE request is made - here is the code I am using WITHOUT THE REDIRECT:
exports.remove = function(req, res) {
var postId = req.params.id;
Post.remove({ _id: postId }, function(err) {
if (!err) {
console.log('notification!');
res.send(200);
}
else {
console.log('error in the remove function');
res.send(400);
}
});
};
remove gets called when an item (a post) is deleted. Everything works fine (I had to use res.send(200) to get it to not hang on the delete request) - but now I am having trouble redirecting. If I use res.redirect('/forum') inside the remove function, like this:
exports.remove = function(req, res) {
var postId = req.params.id;
Post.remove({ _id: postId }, function(err) {
if (!err) {
console.log('notification!');
res.send(200);
}
else {
console.log('error in the remove function');
res.send(400);
}
res.redirect('/forum');
});
};
It registers the redirect as a DELETE request that is trying to delete /forum, like this:
DELETE http://localhost:9000/forum 404 Not Found 4ms
All I am trying to do is refresh the page so that the list of posts is updated after the delete. Can anyone help?
I know this is late, but for anyone who sees this later, you can also manually reset the HTTP method to GET which should also work
exports.remove = function(req, res) {
var postId = req.params.id;
Post.remove({ _id: postId }, function(err) {
if (!err) {
console.log('notification!');
res.send(200);
}
else {
console.log('error in the remove function');
res.send(400);
}
//Set HTTP method to GET
req.method = 'GET'
res.redirect('/forum');
});
};
#ewizard 's solution is great if you can fix this on the front end. However, if you want to fix this on the back end, you can add an optional Status Code argument to res.redirect like so:
res.redirect(303, "/forum");
This redirects for "Undefined Reason" which will default to a GET redirect.
See this SO post for more info.
I got it working on my Angular side with $window.location.href = '/forum'; - just put it in the success function of the $http request that is part of the delete function that gets executed when the "Delete" button is clicked.

express router.get() function SyntaxError

I'm trying to create a route to return JSON data from a JSON-RPC API.
My code:
router.get('/balance', function(req, res, client) {
res.json({
client.getBalance('*', 1, function(err, balance) {
if(err)
console.log(err);
else
console.log('Balance: ', balance);
});
});
});
It's using the npm package node-litecoin. I have required it and created a client var like so:
var client = new litecoin.Client({
host: 'localhost',
port: 9332,
user: 'myaccount',
password: 'mypass'
});
client.getBalance('*', 1, function(err, balance) {
^
SyntaxError: Unexpected token .
Why am I getting this error?
Why am I getting this error?
Because client.getBalance('*', 1, function(err, balance) { cannot be there where you put it.
Lets have a closer look:
res.json({ ... });
The {...} here indicate an object literal. The "content" of the literal has to be a comma separated list of key: value pairs, e.g.
res.json({foo: 'bar'});
You instead put a function call there:
res.json({ client.getBalance(...) });
which simply is invalid.
How can I have the route '/balance' output the client.getBalance() function?
It looks like client.getBalance is an asynchronous function call, hence passing its return value to res.json wouldn't work either. You have to pass the result that you get in the callback to res.json:
router.get('/balance', function(req, res) {
client.getBalance('*', 1, function(err, balance) {
if(err)
console.log(err);
else
console.log('Balance: ', balance);
res.json(balance);
});
});
If you are not very familiar with JavaScript's syntax, I recommend to read the MDN JavaScript Guide.

Categories