How to get value from router request? - angularjs

I have created an angular app. In this app, I want to add a search. for this, I have a textbox and a button. Textbox name is name="search"
I have a get method in API.
router.get('/allActivities', (req, res) => {
Activity.find({ name: req.body.search }, (err, activities) => {
if(err) {
res.json({success: false, message: err});
} else {
if(!activities) {
res.json({success: false, message: 'No recent activities found'});
} else {
res.json({success: true, activities: activities});
}
}
})
});
This is the get request. In this, I'm trying to get the text box value from angular front end
Activity.find({ name: req.body.search }, (err, activities) =>
This is MongoDB
But I'm not getting any output. The matter here is I'm not getting a value for this "req.body.search" which I used to get text box value. can anybody tell me how to do this?
if I put
Activity.find({ name: 'Roshini' }, (err, activities) =>
like this, I'm getting the output. So pretty sure that I'm not getting textbox value to this get method correctly, :/

Html side
<input ng-model="search">
Angular Controller
$http({
method: 'GET',
url: '/allActivities?search='+$scope.search
}).then(function (response) {
$scope.activities = response.data || response
}, function (response) {
alert(response)
}
);
and on backend access it by req.query.search or req.params.search rather than req.body.search

Related

I can't update my contacts

I read some tutorials on MEAN Stack and I'm currently working on one which is almost complete, until I tried my update function. I keep on receiving a 400 message and when i look at the chrome dev tools and under the network tab I read the response which is "_id" is not allowed.
here is the update function
$scope.update = () => {
console.log($scope.contact._id);
$http.put('/api/contacts/updatecontact/' + $scope.contact._id, $scope.contact)
.then(function(data) {
alert('Data was updated Successfully');
refresh();
});
};
here is the api.
app.put('/api/contacts/updatecontact/:id', (req, res) => {
const id = req.params.id;
console.log(req.body.name);
// validation
const { error } = validateInput(req.body);
if (error){
return res.status(400).send(error.details[0].message);
}
const updatedContact = Contact.where({ _id: id });
updatedContact.update({
$set: { name: req.body.name, email: req.body.email
}
}, (err, contact) => {
if(err){
console.log('error occured');
}
res.json(contact);
console.log('contact successfully updated');
});
console.log(updatedContact);
});
hope i can get some help with this.
It seems the node.api is validating the json object that you are passing. Make sure the properties you sent form the client.
Make sure you are not validating or remove the validation on the node.

How to send form data from Angularjs to Django

I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]).
With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem.
$scope.saveUser = function(event) {
postForm({ id: 0 }, $('#FormName'), $scope, function(data) {
})
}
function postForm(postInfo, form, $scope, callback,) {
var postData = new FormData(form.get(0));
$.each(postInfo, function(key, value) {
postData.append(key, value);
});
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: postData,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
headers: {
"X-CSRFToken": app.getStorage("csrftoken")
},
beforeSend: function() {
$('#loading-image').show();
},
complete: function() {
$('#loading-image').hide();
if(typeof saveButtonId !== typeof undefined) {
$('#'+saveButtonId).removeAttr('disabled');
}
},
success: function(data) {
},
error: function(data) {
//
}
});
};
you'd be updating code in your mysite/backend folder to have some incoming route to insert data into django db using some serializer
sorry I don't have more specific details, but just wanted to convey the general idea
Here's some more information on Django serializers: http://www.django-rest-framework.org/api-guide/serializers/
another tutorial on adding an additional route to django could help

Using "$http.get" in ionic App, Response not get proper format

I am using "$http.get" for send request. My API response in browser, it returns what i want. But in Ionic App, it return HTML body tag text.
My Code is:
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi", { params: params }).then(function (data) {
alert(JSON.stringify(data));
}).error(function (data) {
alert(JSON.stringify(data));
});
This is my AngularCode. When i run it in postman, it return valid response. But in Ionic App not Working.
If you want the $http.get, this should work.
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi").then(function (data) {
alert(JSON.stringify(data));
}).error(function (err) {
alert(JSON.stringify(err));
});
However, in this case, what you are trying to do is to login into something. A get request will not work with this. You need to use $http.post at least in this case.

C# with kendo ui - client send file to server

I'm trying to send a .xlsx file to my REST API using Kendo Ui. But I'm lost.
I was able to call my service, but I can't get the file. I believe I'm sending it wrong.
I don't need to save the file. I only need to read the .xlsx file to import the data to my database.
html (don't have a form):
<div>
<input name="files" id="files" type="file" />
<button id="importButton">Import</button>
</div>
js:
$("#files").kendoUpload({
async: {
autoUpload: true
},
select: onSelect
});
$("#importButton").kendoButton({
click: onImport
});
function onImport() {
var formData = new FormData();
jQuery.each(jQuery('#files')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
cache: false,
success: function (result) {
alert("Ok");
},
error: function (result) {
alert("Not Ok");
}
});
}
Server-side:
[HttpPost, Route("import")]
public void Import()
{
var streamProvider = new MultipartMemoryStreamProvider();
Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(streamProvider).ContinueWith((tsk) =>
{
foreach (HttpContent ctnt in streamProvider.Contents)
{
Stream stream = ctnt.ReadAsStreamAsync().Result;
// do something
}
});
}
Got it!
$("#files").kendoUpload({
async: {
withCredentials: false,
saveUrl: url,
autoUpload: true
},
select: onSelect
});
This answer helped me: Cross domain upload
#Brett was right, implement the kendUpload was the way.
I thought the Import button should do the magic, but I only need to use kendoUpload.
Thanks!!

Express + Angular update route: Error: Cannot PUT

I'm trying to update a schema using form, however, both on app.put and app.post (which I've seen as a possible solution) i get
PUT https://myapp-demo.herokuapp.com/api/events/5523da4d97c5000300f6e713 404 (Not Found)
and error from ajax callback
Error: Cannot PUT /api/events/5523da4d97c5000300f6e713
on clientside, I make this request:
$scope.saveEvent = function(id) {
$http.put('../api/events/' + id, $scope.formData)
.success(function (data) {
$scope.events = data;
})
.error(function(data) {
console.log('Error: ' + data);
})
};
In express routes, I do this:
app.put('../api/events/:id', function (req, res){
var user = req.user;
var id = req.params.id;
var update = {
$set: {
title: req.body.title,
description: req.body.description,
}
};
Event.findByIdAndUpdate(id, update, function (err, event) {
if(!event) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
console.log("event updated");
Event.find(function(err, events) {
if (err){
res.send(err)
};
res.json(events);
});
});
});
I tried to pass event._id differently, by using req.params.id and passing id with form like req.body.id, it all leads to the same result. I've also read about creating hidden input for helping method-override to override form methods. However, having this didn't help.
<input type="hidden" name="_method" value="put">
<md-button class="md-raised md-primary" ng-click="saveEvent(eventId)">Save</md-button>
UPDATE
Indeed, the initial proble was in my put route. I've found a new problem now. When I try to update it again, I get
Error: Object {error: "Not found"}
It happens even after I refresh page or restart server.
The following is invalid:
app.put('../api/events/:id'...
It needs to be in reference to the namespace, or in your case the root:
app.put('/api/events/:id'...

Resources