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.
Related
A follow-up on a similar question I posted yesterday. I am trying to delete data from a table in Azure App service. This is my function in my Angular file.
function delName(user) {
//$scope.categories.push(user);
alert("about to delete. Action cannot be undone. Continue?")
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Then I added an HTML button:
<button id="btn-del-evangelist" class="btn btn-default btn" ng-click="delName(user);">Delete User</button>
This is the value of my headers variable:
var config = {
headers: {
'Access-Control-Allow-Origin':'*',
'ZUMO-API-VERSION': '2.0.0'
}
};
But when I tried to run it, the console returns the following error:
which states that the header for ZUMO-API-VERSION must be specified.
Below is my code for GET and POST
GET:
function getNames() {
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', config)
.then(function (res) {
console.log(res);
$scope.people = res.data;
});
}
POST
function addName(user){
//$scope.categories.push(user);
alert("about to post!")
$http.post('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Since I have already specified the header in my variable, I wonder what can be wrong here. Any help will be appreciated.
UPDATE:
I figured out that the Id must be appended to the URL before I can perform delete. However, I need to run a GET to retrieve the ID given the parameters but I am still encountering errors when getting the ID.
This is now my Delete function
function delName(user) {
alert("About to delete. Action cannot be undone. Continue?")
var retrievedId = "";
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' }
})
.then(function (res) {
retrievedId = res.id;
alert(retrievedId);
});
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + retrievedId, config)
.then(function (res) {
$scope.getNames();
});
}
Does anyone know what is wrong in the GET command when getting the ID?
UPDATE 2: I have written instead an Web Method (asmx) that will connect to SQL server to retrieve the ID passing the needed parameters. The ID will be returned as a string literal but in JSON format. Then I called JSON.parse to parse the string into JSON object then assigned the ID to a variable to which I appended in the URL. –
This is now my Delete function after I have written the Web Method.
function delName(user) {
var confirmres = confirm("You are about to delete this record. Action cannot be undone. Continue?");
var retrievedId = "";
if (confirmres == true) {
//get the ID via web service
$http.get('\\angular\\EvangelistsWebService.asmx/GetId', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' },
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.then(function (res) {
$scope.retData = res.data;
var obj = JSON.parse($scope.retData);
angular.forEach(obj, function (item) {
if (item.length == 0)
alert('No data found');
else {
//perform delete after getting the ID and append it to url
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + item.id, config)
.then(function (res) {
$scope.getNames();
});
alert(item.id + ' deleted');
}
});
});
}
}
That is one way that I have learned on how to call HTTP DELETE on AngularJS. But I don't know if that is the optimal one. In any case, that works for me, unless there will be other suggestions.
$http.delete only has one parameter (config), not two (data, config).
Delete API
delete(url, [config]);
vs.
Post API
post(url, data, [config]);
To your updated problem:
To delete an item from your table, it appears the correct url is:
/tables/tablename/:id
Note the : before id.
I have problem with AngularJS. Im working on securing my Java Spring REST web application with Spring-Security. Im stuck on logging page - http post works perfectly using AJAX however it doesnt while using AngularJS.
jQuery(document).ready(function ($) {
$('#login-form').submit(function (event) {
event.preventDefault();
var data = 'username=' + $('#username').val() + '&password=' + $('#password').val();
console.log(data);
$.ajax({
data: data,
timeout: 1000,
type: 'POST',
url: 'http://localhost:8080/OnlineGameStore/login'
}).done(function(data, textStatus, jqXHR) {
console.log("Done!")
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Booh! Wrong credentials, try again!');
});
});
});
This AJAX code works perfectly, the credentials are properly send to the server. However:
angular.module('login').controller('LoginCtrl', function($scope, $http, $location, AuthUser ){
$scope.login = function(){
AuthUser.authenticateUser( $scope.username, $scope.password, $location ).then( function(response){
console.log(response);
});
};
});
angular.module('login').service('AuthUser', function( $http, $location ){
this.authenticateUser = function( username, password, $location ){
var absUrl = $location.absUrl();
console.log(absUrl);
var data = {
username: username,
password: password
};
var config = {
headers : {
'Content-type': 'application/json'
}
return $http.post(absUrl, data, config)
.then(
function(response){
return "Successfully logged!";
},
function(response){
window.alert("Failure!");
});
};
});
this doesnt work - data isnt even properly send to the server, instead of provided username and password all I see are nulls ( and I get 401 all the time ). URL's are the same. Can someone help me solve this?
I also tried sending bare string instead of 'data' object, it also didnt seem to work.
jQuery by default send data with Content-Type: x-www-form-urlencoded and AngularJS $http service send with Content-Type: application/json.
If you want to send data like jQuery then set the request header like this:
var data = {
username: username,
password: password
};
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
return $http.post(absUrl, data)
.then(
function(response){
return "Successfully logged!";
},
function(response){
window.alert("Failure!");
});
Remember this is global configuration for $http service.
I don't know in which technology you are running your backend, but it's often better to use default AngularJS header application/json.
What is difference?
Data in application/x-www-form-urlencoded is send by uri for example: ?parm1=1&parm2=2&parm3=3
In .NET MVC WebAPI this will be binded for:
[HttpPost]
public HttpResponseMessage Simple(int parm1, int parm2, int parm3) {
}
Data in Content-Type: application/json is send by payload in JSON format for example: { parm1: 1, parm2: 2, parm3: 3 }
In .NET MVC WebAPI this will be binded for:
[HttpPost]
public HttpResponseMessage Simple(Parameters parameters) {
}
how come its sending data to mongo if I $http.post directly in the controller?
$http.post('/api/users/', vm.newUser).success(function(response){
But using the code below doesn't seems to work, it's not passing any value but generates ID in mongoDB
vm.signupNewUser = function () {
signupService.signupNewUser(vm.newUser).success(function(response){
console.log(vm.newUser);
}).error(function(err){
console.log(err);
})
}
service:
function _signupNewUser(username, password, email, fname, lname){
var data = {
username: username,
password: password,
email: email,
fname: fname,
lname: lname
}
return $http({
method: 'POST',
url: '/api/users',
data: data
})
}
Edit: this seems to fix it, but not sure how is it different from using a direct $http.post and just passing vm.newUser. But using factory I have to pass in vm.newUser.username and etc. I don't think passing the vm like this is ideal but please correct me if I'm wrong.
vm.signupNewUser = function () {
signupService.signupNewUser(vm.newUser.username, vm.newUser.password, vm.newUser.email, vm.newUser.fname, vm.newUser.lname)
.then(function(response){
console.log(response);
console.log(vm.newUser);
});
}
I am having a 404 issue with my NodeJS API. I don't know if I am quite doing it right, I tried referring to documentation, and I feel like it's close.
MongoDB Schema
var User = mongoose.Schema({
local: {
email: String,
password: String,
handle: String,
pic: {data: Buffer, contentType: String}
}
});
NodeJS UPDATE API
app.post('/api/users', function(req, res, user) {
User.update({email : user.email,
password : user.password,
handle : user.handle,
pic : user.pic},
{$set: {
email : req.body.email,
password : req.body.email,
handle : req.body.handle,
pic : req.body.pic,
done : false
}
}, function(err, users) {
if(err) {
res.send(err);
}
res.redirect('/profile');
});
});
Controller POST API call
$scope.editProfile = function() {
$http.post('/api/users', $scope.editFormData)
.success(function(data) {
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Any suggestions?
You are not doing a post call correct. You can't pass your post object in the URL. Your node post should look like this.
app.post('/api', upload.array(), function(req, res) {
var body = req.body; //body will be your post object
});
For a post to work you need to make sure you have the proper things added to your Node Project. The above example is using ExpressJS with require('body-parser') and require('multer'). The example you are showing will never show as a true path. For reference here is how you would do a get in node.
app.get('/getcall/*', function(){
// the * denotes any singleton parameter you wanted to pass in.
})
Here are the references I use in all my node projects. These are the basics.
var express = require('express'),
bodyParser = require('body-parser'),
multer = require('multer'),
helmet = require('helmet'),
upload = multer(),
path = require('path'),
request = require('request'),
app = express(),
http = require('http');
Also as for your angular call an $http.post looks like this and you should be using .then instead of .success.
$http.post('/api', $scope.editFormData)
.then(function successCallback(resp) {
console.log(resp.data)
}, function errorCallback(resp) {
console.log(resp)
});
I am new to AngularJS and Single Page Application in ASP.NET MVC. I am using Web API as service and token based authentication for login. When I am calling authentication URL as below, it is not returning response and then appears to b null.
var data = {
grant_type: "password",
username: userName,
password: loginPassword
};
$http.post("/Token", data)
.then(function (response) {
alert(JSON.stringify( response.data));
return response.data;
});
However when I am passing data as below, it return the response.
var data = "grant_type=password&username=" + userName + "&password=" + loginPassword;
$http.post("/Token", data)
.then(function (response) {
alert(JSON.stringify( response.data));
return response.data;
});
Question: What is actually happening both cases that first is not responding at all, while other is responding?