I get this error, I found many thread with the same message, but it never seems to match my case, and I didn't manager to solve it.
Basivally, everything was ok until I tried to make 1 form for create and update a 'Car' object.
Here is a presentation of my app (build from this template: https://github.com/linnovate/mean):
/public/js/config.js:
[...]
.state('edit car', {
url: '/cars/:carId/edit',
templateUrl: 'views/cars/edit.html'
})
.state('create car', {
url: '/cars/create',
templateUrl: 'views/cars/edit.html'
})
/public/js/services/mycars.js (don't really know what services are used for...):
//Cars service used for car REST endpoint
angular.module('mean.mycars').factory('Cars', ['$resource', function($resource) {
return $resource('cars/:carId', {
carId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
public/js/controllers/mycars.js:
angular.module('mean.mycars').controller('MyCarsController', ['$scope', '$http', '$stateParams', '$location', 'Global', 'Cars',
function ($scope, $http, $stateParams, $location, Global, Cars) {
$scope.findOneOrCreate = function () {
// create a new car
var car = new Cars({
id : null,
marque: this.marque,
modele: this.modele,
desc: this.desc
});
// put new car in scope
$scope.car = car;
// if there is a param, search for the car (mode update)
if ($stateParams.carId !== null){
Cars.get({
carId: $stateParams.carId
}, function(carTmp) {
// put the result in scope
$scope.car = carTmp;
});
}
};
$scope.createOrUpdate = function () {
var car = $scope.car;
if (car.id !== null) {
// update
if (!car.updated) {
car.updated = [];
}
car.updated.push(new Date().getTime());
car.$update(function () {
$location.path('cars/' + car._id);
});
}
else {
//Create
car.$save(function (response) {
$location.path('cars/' + response._id);
});
}
};
And finally my view: edit.html:
<section data-ng-controller="MyCarsController" data-ng-init="findOneOrCreate()">
<form class="form-horizontal col-md-6" role="form" data-ng-submit="createOrUpdate()">
<div class="form-group">
<label for="title" class="col-md-2 control-label">Title</label>
<div class="col-md-10">
<input type="text" class="form-control" data-ng-model="car.modele" id="title" placeholder="Title" required>
</div>
</div>
<div class="form-group">
<label for="content" class="col-md-2 control-label">Content</label>
<div class="col-md-10">
<textarea data-ng-model="car.marque" id="content" cols="30" rows="10" placeholder="Content" class="form-control" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</section>
Edit to add infos:
The web Services are supposed to return only one car (but not sure if they do), here they are:
exports.car = function(req, res, next, id) {
Car.load(id, function(err, car) {
if (err) return next(err);
if (!car) return next(new Error('Failed to load car ' + id));
req.car = car;
next();
});
};
exports.create = function(req, res) {
var car = new Car(req.body);
car.user = req.user;
car.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
car: car
});
} else {
res.jsonp(car);
}
});
};
exports.update = function(req, res) {
var car = req.car;
car = _.extend(car, req.body);
car.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
car: car
});
} else {
res.jsonp(car);
}
});
};
Error message appears when I go to /cars/create, not when I go to /cars/:carsId/edit:
Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array
http://errors.angularjs.org/1.2.15/$resource/badcfg?p0=object&p1=array
Is your web service returning an array? The get method expects only one object to be returned, and the same with your PUT request if you're returning something. If you're expecting multiple you will need to specify isArray: true in your service method in mycars.js. See example here: http://docs.angularjs.org/api/ngResource/service/$resource
Related
This question already has answers here:
Angular $http is sending OPTIONS instead of PUT/POST
(2 answers)
Closed 5 years ago.
I'm new to the AngularJS. I'm using AngularJS 1.3.15 version. When I try to call an api with PUT method, It's generating OPTIONS request. I don't know where I'm doing mistake. I tried so many methods which is suggested in Stockoverflow, but still I'm not getting anything. Please help me to resolve this issue. below are my Controller, Models, html files and Chrome developer tool network activity screenshot.
Controller file users.js
'use strict';
mmlApp_users.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/users/update/:userId', {
templateUrl: 'views/users/update.html',
controller: 'update',
resolve: {
user: function(users, $route){
var userId = $route.current.params.userId
return users.getUser(userId);
}
}
})
.otherwise({
redirectTo: '/users/index'
});
}]);
Model file - users.js
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route', function($http, $location, $route){
var obj = {};
obj.getUser = function(userId){
return $http.get(serviceBase + 'users/view/'+userId);
};
obj.updateUser = function(user){
var config = {
headers: {
'Content-Type': 'application/json'
}
};
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
$http.put(serviceBase + 'users/update/'+user.id+'?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13', userParams, config)
.then(successHandler).catch(errorHandler);
function successHandler(){
$location.path('/users/index');
}
function errorHandler(){
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
Views - update.html
<div>
<h1>{{title}}</h1>
<p>{{ message}}</p>
<form role="form" name="myForm">
<div class="row">
<div class= "form-group col-md-6" ng-class="{error: myForm.first_name.$invalid}">
<label> First Name: </label>
<div>
<input name="first_name" ng-model="user.first_name" type= "text" class= "form-control" placeholder="First Name" required/>
<span ng-show="myForm.first_name.$dirty && myForm.first_name.$invalid" class="help-inline">First Name Required</span>
</div>
</div>
<div class= "form-group col-md-6" ng-class="{error: myForm.last_name.$invalid}">
<label> Last Name: </label>
<div>
<input name="last_name" ng-model="user.last_name" type= "text" class= "form-control" placeholder="Last Name" required/>
<span ng-show="myForm.last_name.$dirty && myForm.last_name.$invalid" class="help-inline">Last Name Required</span>
</div>
</div>
</div>
....
....
....
Cancel
<button ng-click="updateUser(user);" ng-disabled="myForm.$invalid" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
In chrome developer tool network activity screenshot -
try in your factory:
(function () {
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route','$httpParamSerializer',
function ($http, $location, $route, $httpParamSerializer) {
var obj = {};
obj.getUser = function (userId) {
return $http.get(serviceBase + 'users/view/' + userId);
};
obj.updateUser = function (user) {
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
var req = {
method: 'PUT',
url: serviceBase + 'users/update/' + user.id + '?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: $httpParamSerializer(userParams)
};
$http(req)
.then(successHandler)
.catch(errorHandler);
function successHandler() {
$location.path('/users/index');
}
function errorHandler() {
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
})();
And Goog Lock :)
I've been making node.js website using angular template.
But I can't create data on DB(Mongo).
Here are code.
node routing.
var Property = mongoose.model('Property');
var jwt = require('express-jwt');
var auth = jwt({
secret: 'SECRET',
userProperty: 'payload'
});
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId; //Have also tried Schema.Types.ObjectId, mongoose.ObjectId
// Property Routing Management
router.post('/property', auth, function(req, res, next) {
var property = new Property(req.body);
console.log("checkpoint api");
property.save(function(err, property) {
if (err) {
return next(err);
}
return res.json(property);
})
});
AngularJS HTML
<form class="form-horizontal">
<label class="col-md-3 control-label" for="title">Member Name:</label>
<div class="col-md-5">
<input id="notific8_text" type="text" class="form-control" value="" placeholder="" ng-model="property.user">
</div>
<button ng-click="updateProperty()"> Submit </button>
</form>
AngularJS Controller.
angular.module('MainApp').controller('EditPropertyController', [
'$scope',
's_property',
's_auth',
'$state',
'$location',
function($scope, s_property, s_auth, $state, $location) {
$scope.updateProperty = function()
{
var data = {
user: $scope.property.user,
}
s_property.create(data);
};
}]);
and AngularJS service.
angular.module('MetronicApp')
.factory('s_property', [
'$http',
'$window',
's_auth',
function($http, $window, s_auth) {
var service = {
all_properties: [],
current_property: {}
};
service.create = function(property) {
console.log("checkpoint service");
return $http.post('/api/v1/property', property);
};
};
]);
When I input data in the input tag and click the submit button, chrome console shows like this
POST http://localhost:3000/property 401 (Unauthorized)
What is the mistake?
Cheers.
PS
this is
angular.module('MainApp')
.factory('s_auth', ['$http', '$window', function($http, $window){
var auth = {};
auth.saveToken = function (token) {
$window.localStorage['current-user-token'] = token;
};
auth.getToken = function() {
return $window.localStorage['current-user-token'];
};
}
service
Looks like you are not sending the JWT token to your backend.
TO be sending it try adding headers { authorization: "{TOKEN}"} in your post request
I'm developing a simple CRUD application with MEAN stack. So the scenario is a user post a data to the server and it will render the data in real-time. Everything works fine but whenever I refresh the page ,
It will sort of loads all the content, every time it tries to fetch the data. I guess this is a caching problem.
So what I want to achieve is, every time a user refresh the page or go to another link, the content will be there without waiting for split seconds.
Here's the link to test it on, try to refresh the page
https://user-testing2015.herokuapp.com/allStories
and the code
controller.js
// start our angular module and inject our dependecies
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function(Story, $routeParams, socketio) {
var vm = this;
vm.stories = [];
Story.all()
.success(function(data) {
vm.stories = data;
});
Story.getSingleStory($routeParams.story_id)
.success(function(data) {
vm.storyData = data;
});
vm.createStory = function() {
vm.message = '';
Story.create(vm.storyData)
.success(function(data) {
// clear the form
vm.storyData = {}
vm.message = data.message;
});
};
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
.controller('AllStoryController', function(Story, socketio) {
var vm = this;
Story.allStories()
.success(function(data) {
vm.stories = data;
});
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
service.js
angular.module('storyService', [])
.factory('Story', function($http, $window) {
// get all approach
var storyFactory = {};
var generateReq = function(method, url, data) {
var req = {
method: method,
url: url,
headers: {
'x-access-token': $window.localStorage.getItem('token')
},
cache: false
}
if(method === 'POST') {
req.data = data;
}
return req;
};
storyFactory.all = function() {
return $http(generateReq('GET', '/api/'));
};
storyFactory.create = function(storyData) {
return $http(generateReq('POST', '/api/', storyData));
};
storyFactory.getSingleStory = function(story_id) {
return $http(generateReq('GET', '/api/' + story_id));
};
storyFactory.allStories = function() {
return $http(generateReq('GET', '/api/all_stories'));
};
return storyFactory;
})
.factory('socketio', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
}
};
}]);
api.js (both find all object and single object)
apiRouter.get('/all_stories', function(req, res) {
Story.find({} , function(err, stories) {
if(err) {
res.send(err);
return;
}
res.json(stories);
});
});
apiRouter.get('/:story_id', function(req, res) {
Story.findById(req.params.story_id, function(err, story) {
if(err) {
res.send(err);
return;
}
res.json(story);
});
});
For api.js whenever I refresh the page for '/all_stories' or go to a '/:story_id' it will load the data for split seconds.
allStories.html
<div class="row">
<div class="col-md-3">
</div>
<!-- NewsFeed and creating a story -->
<div class="col-md-6">
<div class="row">
</div>
<div class="row">
<div class="panel panel-default widget" >
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>
<h3 class="panel-title">
Recent Stories</h3>
<span class="label label-info">
78</span>
</div>
<div class="panel-body" ng-repeat="each in story.stories | reverse" >
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-xs-10 col-md-11">
<div>
<div class="mic-info">
{{ each.createdAt | date:'MMM d, yyyy' }}
</div>
</div>
<div class="comment-text">
<h4>{{ each.content }}</h4>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3">
</div>
The loading problem you see is that the data is fetched after the view has been created. You can delay the loading of the view by using the resolve property of the route:
.when('/allStories', {
templateUrl : 'app/views/pages/allStories.html',
controller: 'AllStoryController',
controllerAs: 'story',
resolve: {
stories: function(Story) {
return Story.allStories();
}
}
})
Angular will delay the loading of the view until all resolve properties have been resolved. You then inject the property into the controller:
.controller('AllStoryController', function(socketio, stories) {
var vm = this;
vm.stories = stories.data;
});
I think you should use local storage. suited module - angular-local-storage
The data is kept aslong you or the client user clean the data,
Usage is easily:
bower install angular-local-storage --save
var storyService = angular.module('storyService', ['LocalStorageModule']);
In a controller:
storyService.controller('myCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {
localStorageService.set(key, val); //return boolean
localStorageService.get(key); // returl val
}]);
Match this usage to your scenario (for example - put the stories array on and just append updates to it)
I'm working on building a little app that accepts input from a form (the input being a name) and then goes on to POST the name to a mock webservice using $httpBackend. After the POST I then do a GET also from a mock webservice using $httpBackend that then gets the name/variable that was set with the POST. After getting it from the service a simple greeting is constructed and displayed back at the client.
However, currently when the data gets displayed now back to the client it reads "Hello undefined!" When it should be reading "Hello [whatever name you inputed] !". I used Yeoman to do my app scaffolding so I hope everyone will be able to understand my file and directory structure.
My app.js:
'use strict';
angular
.module('sayHiApp', [
'ngCookies',
'ngMockE2E',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.run(function($httpBackend) {
var name = 'Default Name';
$httpBackend.whenPOST('/name').respond(function(method, url, data) {
//name = angular.fromJson(data);
name = data;
return [200, name, {}];
});
$httpBackend.whenGET('/name').respond(name);
// Tell httpBackend to ignore GET requests to our templates
$httpBackend.whenGET(/\.html$/).passThrough();
});
My main.js:
'use strict';
angular.module('sayHiApp')
.controller('MainCtrl', function ($scope, $http) {
// Accepts form input
$scope.submit = function() {
// POSTS data to webservice
setName($scope.input);
// GET data from webservice
var name = getName();
// Construct greeting
$scope.greeting = 'Hello ' + name + ' !';
};
function setName (dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
// GET name from webservice
function getName () {
$http.get('/name').
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
});
My main.html:
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<img src="../images/SayHi.png" class="logo" />
</div>
</div>
<div class="row text-center">
<div class="col-xs-10 col-xs-offset-1 col-md-4 col-md-offset-4">
<form role="form" name="greeting-form" ng-Submit="submit()">
<input type="text" class="form-control input-field" name="name-field" placeholder="Your Name" ng-model="input">
<button type="submit" class="btn btn-default button">Greet Me!</button>
</form>
</div>
</div>
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p class="greeting">{{greeting}}</p>
</div>
</div>
At the moment your getName() method returns nothing. Also you cant just call getName() and expect the result to be available immediately after the function call since $http.get() runs asynchronously.
You should try something like this:
function getName () {
//return the Promise
return $http.get('/name').success(function(data) {
$scope.error = false;
return data;
}).error(function(data) {
$scope.error = true;
return data;
});
}
$scope.submit = function() {
setName($scope.input);
//wait for the Promise to be resolved and then update the view
getName().then(function(name) {
$scope.greeting = 'Hello ' + name + ' !';
});
};
By the way you should put getName(), setName() into a service.
You can't return a regular variable from an async call because by the time this success block is excuted the function already finished it's iteration.
You need to return a promise object (as a guide line, and preffered do it from a service).
I won't fix your code but I'll share the necessary tool with you - Promises.
Following angular's doc for $q and $http you can build yourself a template for async calls handling.
The template should be something like that:
angular.module('mymodule').factory('MyAsyncService', function($q, http) {
var service = {
getNames: function() {
var params ={};
var deferObject = $q.defer();
params.nameId = 1;
$http.get('/names', params).success(function(data) {
deferObject.resolve(data)
}).error(function(error) {
deferObject.reject(error)
});
return $q.promise;
}
}
});
angular.module('mymodule').controller('MyGettingNameCtrl', ['$scope', 'MyAsyncService', function ($scope, MyAsyncService) {
$scope.getName = function() {
MyAsyncService.getName().then(function(data) {
//do something with name
}, function(error) {
//Error
})
}
}]);
I believe Angular is loading the page before it receives all the information from JSONP. If I refresh the page a couple of times I do get the information to display; however, it is not constant. My code is almost the same as the code I am using on my projects page which does not have the same issue.
HTML:
<div class="container">
<div class="row push-top" ng-show="user">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1">
<div class="well well-sm">
<div class="row">
<div class="col-sm-3 col-md-2">
<img ng-src="[[ user.images.138 ]]" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-sm-7 col-md-8">
<h4 ng-bind="user.display_name"></h4>
<h5 ng-bind="user.occupation"></h5>
<i class="fa fa-map-marker"></i>
<cite title="[[ user.city ]], [[ user.country ]]">[[ user.city ]], [[ user.country ]]</cite>
<br>
<strong ng-bind="user.stats.followers"></strong> Followers, <strong ng-bind="user.stats.following"></strong> Following
<hr>
<p style="margin-top:10px;" ng-bind="user.sections['About Me']"></p>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScipt:
'use strict';
angular.module('angularApp')
.controller('AboutCtrl', function ($scope, $window, Behance) {
$scope.loading = true;
Behance.getUser('zachjanice').then(function (user) {
$scope.user = user;
$scope.loading = false;
}, function (error) {
console.log(error);
$scope.loading = false;
$scope.user = null;
});
$scope.gotoUrl = function (url) {
$window.location.href = url;
};
});
You can see the page in question at: http://zachjanice.com/index.html#/about. Thanks in Advance.
As requested here is the behance service:
'use strict';
angular.module('angularApp')
.factory('Behance', function ($http, $q, localStorageService, BEHANCE_CLIENT_ID) {
// Should be called to refresh data (for testing purposes)
// localStorageService.clearAll();
// Public API
return {
// Get a list of projects
getProjects: function (config) {
var pageNum = 1;
if (angular.isObject(config) && angular.isDefined(config.page)) {
pageNum = config.page;
}
var _projects = $q.defer(),
_storedProjects = localStorageService.get('Projects_Page_');
if (_storedProjects !== null) {
_projects.resolve(_storedProjects);
} else {
$http.jsonp('https://www.behance.net/v2/users/zachjanice/projects', {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK',
'page': pageNum
}
})
.then(function (response) {
if (response.data.http_code === 200 && response.data.projects.length > 0) {
// console.log('getting page', _page);
_projects.resolve(response.data.projects);
localStorageService.add('Projects_Page_' + pageNum, response.data.projects);
}
});
}
return _projects.promise;
},
// Get project with id
getProject: function (id) {
var _project = $q.defer();
$http.jsonp('https://www.behance.net/v2/projects/' + id, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_project.resolve(data.project);
});
return _project.promise;
},
// Get project with id
getUser: function (username) {
var _user = $q.defer();
$http.jsonp('https://www.behance.net/v2/users/' + username, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_user.resolve(data.user);
});
return _user.promise;
}
};
});
Anthony Chu supplied no support, so I found the answer myself. The issue was not the Behance Service, but the Projects Controller like I had originally stated.
I changed $scope.loading under the call for the service from false to true. Works every time.