when i submit signup form using postman it works fine, but when i try to submit using the below code it shows some error, im unable to figure it out, anyone please help me?
.controller('RegisterCtrl', function($scope, AuthService, $state, $http) {
$scope.user = {
name: '',
mobile:'',
email:'',
password:''
};
$scope.signup = function() {
$http.post("http://localhost:8080/api/signup", $scope.user, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
};
})
when i inspect chrome browser it logs the below error:
angular.js:14362 Error: Unexpected request: POST http://localhost:8080/api/signup
No more request expected
at $httpBackend (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-mocks.js:1402:9)
at sendReq (http://localhost:3000/bower_components/angular/angular.js:12178:9)
at serverRequest (http://localhost:3000/bower_components/angular/angular.js:11930:16)
at processQueue (http://localhost:3000/bower_components/angular/angular.js:16689:37)
at http://localhost:3000/bower_components/angular/angular.js:16733:27
at Scope.$eval (http://localhost:3000/bower_components/angular/angular.js:18017:28)
at Scope.$digest (http://localhost:3000/bower_components/angular/angular.js:17827:31)
at ChildScope.$apply (http://localhost:3000/bower_components/angular/angular.js:18125:24)
at HTMLInputElement.<anonymous> (http://localhost:3000/bower_components/angular/angular.js:26813:23)
at HTMLInputElement.dispatch (http://localhost:3000/bower_components/jquery/dist/jquery.js:4435:9) Possibly unhandled rejection: {}(anonymous function) # angular.js:14362(anonymous function) # angular.js:10859processChecks # angular.js:16715$eval # angular.js:18017$digest # angular.js:17827$apply # angular.js:18125(anonymous function) # angular.js:26813dispatch # jquery.js:4435elemData.handle # jquery.js:4121
As already pointed out, you're lacking a lot of important details in your description. My best guess is that your endpoint is expecting your user object to be named "user", in which case your post call should look more like the following:
$http.post(
"http://localhost:8080/api/signup",
{ user: $scope.user },
);
Related
I have created a simple RESTful service in .Net which is hosted here.
I am trying to invoke getByName action from my angularjs code. But, angularjs code is invoking default 'get' instead of 'getByName'
AngularJs code:
app.factory('UserResourceSvc',function($resource){
var baseApiUrl = "http://publicapitest.azurewebsites.net/";
//var baseApiUrl = "http://localhost:92/"
return $resource( baseApiUrl + 'api/Employee/:id',{id: "#id"},
{
getByName : {method: 'GET', params: {} , isArray: false}
}
);
});
I am invoking below function on button click to trigger API call.
$scope.getByName = function(){
UserResourceSvc.getByName(function(data){
debugger;
})
}
I am getting below error message :
angular.js:14794 Error: [$resource:badcfg] Error in resource configuration for action `getByName`. Expected response to contain an object but got an array (Request: GET http://publicapitest.azurewebsites.net/api/Employee)
http://errors.angularjs.org/1.6.7/$resource/badcfg?p0=getByName&p1=object&p2=array&p3=GET&p4=http%3A%2F%2Fpublicapitest.azurewebsites.net%2Fapi%2FEmployee
at angular.js:116
at $http.then.response.resource (angular-resource.js:757)
at processQueue (angular.js:17145)
at angular.js:17193
at Scope.$digest (angular.js:18331)
at Scope.$apply (angular.js:18628)
at done (angular.js:12619)
at completeRequest (angular.js:12863)
at XMLHttpRequest.requestLoaded (angular.js:12780) "Possibly unhandled rejection: {}"
When I checked in fiddler call is going to 'http://publicapitest.azurewebsites.net/api/Employee' instead of 'http://publicapitest.azurewebsites.net/api/Employee/getByName'
Am I missing anything?
You should specify method url as follows:
getByName : {method: 'GET', url: baseApiUrl + 'api/Employee/getByName', params: {} , isArray: false}
I'm pretty new in angularJs, in my ionic
app I try to post
a json to my app symfony fosrestbundle my app is correctly config.
but when I send my post the console
shows me this error message:
XMLHttpRequest cannot load
http://127.0.01/gl/web/api/articles/5/comments . response for preflight has invalide status 405
I'm going crazy! does anyone have any
idea?!thanks a lot for the attention
how are you doing it?
First you need to bind the function to your html like this:
<button class="button button-energized" ng-click="login()">Login</button>
It's recomendded to use a service to do http calls, but you need to inject it (LoginService) in your controller:
.controller('LoginCtrl', function($scope, LoginService) {
$scope.login = function() {
LoginService.loginUser($scope.data.user, $scope.data.password)
.then(function (data) {
//grant access to the app
});
};
});
And in your service:
.factory('LoginService', function($http) {
return {
loginUser: function(user, password) {
return $http.post('http://mydomain/login', {
user: user,
password: password
});
}
};
I have the following function in my service:
myapp.service('addParentService', function ($http) {
vm.returnParent = function ($http) {
for (i in vm.parent) {
//alert('getValues : ' + vm.parent[i].name);
}
var data = { name: 'Jeff', email: 'jv#test.com', phone: '5551212', carrierName: 'ATT' };
$http.post(
'http://localhost:10000/api/people/PostRegister/',
JSON.stringify(data),
{
headers: {
'Content-Type': 'application/json'
}
}
).success(function (data) {
alert(result);
});
});
I ran into the issue where I wasn't injecting $http. Now when I run this function I get the following error:
Unable to get property 'post' of undefined or null reference
This my controller:
myapp.controller('AddParentController', function ($scope,$http, addParentService) {
$scope.addParentService = addParentService;
});
You need to inject $http in your service, if you haven't already. No need to inject it on your controller if you're not invoking it from there (which I guess you're not doing, because if you are, what's the point in making a new service...?)
However, you're including $http (which is a service) as a parameter of your returnParent function; that's why the undefined or null reference error pops up.
So, your first line of code should be vm.returnParent = function () {
Good luck!
$http is a service. Include angular-resource.js also in your project/file. Then the error will not be there.
Also you need to inject ngResource to your module.
Refer this link for specific details:
https://docs.angularjs.org/tutorial/step_11
Abhilash D K
MCP
Not able to get angular to read in an object fetched via service. Error message in brower is really vauge, doesn't reference any of my code lines. I checked via Chrome Developer tools and the api call is getting made. Any ideas?
Error message:
TypeError: undefined is not a function
at copy (http://127.0.0.1:5000/static/lib/angular/angular.js:593:21)
at http://127.0.0.1:5000/static/lib/angular/angular-resource.js:410:19
at wrappedCallback (http://127.0.0.1:5000/static/lib/angular/angular.js:6846:59)
at http://127.0.0.1:5000/static/lib/angular/angular.js:6883:26
at Object.Scope.$eval (http://127.0.0.1:5000/static/lib/angular/angular.js:8057:28)
at Object.Scope.$digest (http://127.0.0.1:5000/static/lib/angular/angular.js:7922:25)
at Object.Scope.$apply (http://127.0.0.1:5000/static/lib/angular/angular.js:8143:24)
at done (http://127.0.0.1:5000/static/lib/angular/angular.js:9170:20)
at completeRequest (http://127.0.0.1:5000/static/lib/angular/angular.js:9333:7)
at XMLHttpRequest.xhr.onreadystatechange (http://127.0.0.1:5000/static/lib/angular/angular.js:9303:11)
Service:
angular.module('angularFlaskServices', ['ngResource'])
.factory('Pic', function($resource) {
return $resource('/api/pic/:picId', {}, {
query: {
method: 'GET',
params: { picId: '' },
isArray: true
}
});
})
;
Angular Controller:
function ProfileController($scope, Pic) {
var picsQuery = Pic.get(function(pics) {
$scope.pics = pics;
});
}
Flask View:
#app.route('/api/pic/')
def on_recent():
if not session.has_key('access_token'):
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=session['access_token'])
recent_media, next = api.user_recent_media()
print recent_media
photos = []
for media in recent_media:
if (media.type != "video"):
photos.append({"picId": 1, "url": media.get_low_resolution_url()})
except Exception as e:
print(e)
return json.dumps(photos)
Your service code looks good but I am not sure if you have all of your dependencies injected properly.
var app = angular.module('myApp', ['angularFlaskServices']);
app.controller('ProfileController', [
'$scope',
'Pic',
function($scope, Pic) {
var picsQuery = Pic.get(function(pics) {
$scope.pics = pics;
});
}]);
I'm just beginning to understand Angularjs and planning to build an app. I'm really a PHP programmer and have little background in javascript. Angularjs was introduced to me by a friend. I was warned that I have to also learn its Jasmine/karma testing before the functionality of the app gets bigger. So here goes, for now I have a $http post which submits an email and a password which if success return a token. Basically if success will redirect the user to the user/profile page
Controller code:
function MainCtrl($scope, $location, Api, localStorageService, Security) {
$scope.loginUser = function () {
Api.authenticatePlayer({
email : $scope.main.email,
password : $scope.main.password
}).then(function (result){
//success
$location.path('/user/profile');
}, function(result) {
//error also this will catch error 400, 401, and 500
console.log(result.data);
});
};
}
And here is my testscript:
beforeEach(function() {
module('myApp.services'),
module("myApp.controllers")
});
beforeEach(inject(function($controller, $rootScope, $location, Api, localStorageService, $httpBackend, Security) {
this.$location = $location;
this.$httpBackend = $httpBackend;
this.scope = $rootScope.$new();
this.redirect = spyOn($location, 'path');
$controller("MainCtrl", {
$scope : this.scope,
$location : $location,
localStorageService : localStorageService,
Security : Security
});
}));
describe("successfully logging in", function () {
it("should redirect you to /user/profile", function() {
//arrange
var postData = {
email : this.scope.main.email,
password : this.scope.main.password
}
this.$httpBackend.expectPOST('login', postData).respond(200);
//act
this.scope.loginUser();
this.$httpBackend.flush();
//assert
expect(this.redirect).toHaveBeenCalledWith('/user/profile');
});
});
Here is my service.js code:
return {
/**
* Authenticate player
* #param object postData Email and password of the user
* #return object
*/
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
}
}
The testscript failed :(.
Here is the error:
Chrome 24.0 (Linux) controller: MainCtrl successfully logging in should redirect you to /user/profile FAILED
Error: Unexpected request: POST http://domain.com/auth/player
Expected POST login
Can anyone please help. So sorry for the trouble though.
So, this is because Api.authenticatePlayer is calling to a different path than what you are expecting.
Your test should have this instead:
this.$httpBackend.expectPOST('http://domain.com/auth/player', postData).respond(200);
Basically, in your test, $httpBackend is a mock of the code that would call your API. You get to say "When my code calls this URL, respond with _". In this code, you are saying that you expect the post to happen and to return an empty response of 200. You could replace "200" with the json payload that you want to pretend that the server responded with.