This is probably a very obvious mistake but I don't understand what's going on:
Server side:
this.app.get('/ripple/dataapiV2/reports',function(req,res) {
console.log("Send REPORTS!!");
res.status(200).send("plouf");
});
Client side, simple backbone model:
var RippleAccountTransactionStats = Backbone.Model.extend({
initialize: function(attr,issuer) {
this.url= config.rippledataapi.account_transaction_stats.urlModel;
}
});
The url is the right one when I fetch "SEND REPORTS" is visible in server console.
But front side the backbone fetch error is triggered:
var model = new RippleAccountTransactionStat({id:account.id},account.address);
var xhr = model.fetch({
success: function(model,response) {
console.log("responssseee",response);
self.add(model);
},
error: function(res,err) {
console.log("account_transaction_stats fetch error", err,res);
}
});
I know it's hard to guess with only that information but really I have no clue why it's not workign properly. If anyone has an hint/clue it would be awesome. thanks in advance.
Weird thing responseText receive the text "plouf" but it's in the error callback I don't get it
backbone wants json
res.status(200).send(JSON.stringify(someobject));
and then success is triggered
Related
Hi I am developing Angularjs application and getting some data from Web API. I am able to receive data. I can confirm this because i can see in fiddler and browser developer tool as well. Below is my code. I am returning data as json from web api. I am returning below object.
return Request.CreateResponse(HttpStatusCode.OK, obj);
Object obj contains some fields(data);
In browser i can see response as below.
{"ID":11,"project_id":1,"levels":1,"icon":1,"description":1,"summary":1,"output":1,"owner":1,"role":1,"objectives":1,"reporting":1,"performance_indicators":1,"success":0,"Created":"0001-01-01T00:00:00","Updated":"0001-01-01T00:00:00"}
This is my angular code.
var saveSubs = ProjectSetting_Service.AddProcessSettings(sub);
saveSubs.then(function (data) {
alert((data.data));
alert((data.obj));
}, function (error) {
})
This is my service.js code
this.AddProcessSettings = function (sub) {
$http.post('/api/NCT_ProcessSettings/', sub).success(function (response) { alert(response); });
}
In alert i want to see response data. May i get some help? Any help would be appreciated. Thank you.
According your response, it does not have data in it,
just put the alert as,
var saveSubs = ProjectSetting_Service.AddProcessSettings(sub);
saveSubs.then(function (data) {
alert((data));
alert((data.project_id));
}, function (error) {
})
UPDATE
Your services is not returning anything, just change the service response to return it,
then you can access the data like alert(data.data);
WORK AROUND IS AT THE BOTTOM
Original problem
There are question like this all over the web and none of them really have answer for me. I can't get an http PATCH operation to work using angular to save my life. I've implemented $http, with shortcut $http.patch and without using the config object method:PATCH. I've used $resource by adding a custom method. And I've implemented Restangular using their patch and I'm getting the same error. I have the correct Content-Type as suggested in other posts. I think it's safe to say at this point, it's something I'm missing. I'm getting the same "404" message via postman when trying to patch. I can PUT, GET, POST, and DELETE, but not PATCH.
In the following images you can see that the resource exists for GET. But when trying to patch I get 404. Browsing to that endpoint shows the record. Which is stored in Mongodb.
Here's some code snippets:
Resangular GET:
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
Restangular Patch:
var data = {
corporiumId: $scope.newBlock
};
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.patch(data).then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
$http attempt using config object:
controller code:
httpCorporiumSrv.updateCorporiumId('/corporium-mgmnts/' + $scope.params.id, data)
.then(handleUpdateSuccess)
.catch(handleUpdateError);
service code, tried forcing the content-type header but got same result
with or without it:
function updateCorporiumId(url, data) {
return $http({
method: 'PATCH',
url: url,
data: angular.toJson(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
//transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Using the .patch shortcut:
function updateCorporiumId(url, data) {
return $http.patch(url, data, {
transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Thing is I've tried this every which way I know how. I don't even know how to start debugging any more. I'm just getting 404 on a resource that does exist. Any suggestions on what might be happening to my request would be great.
Resolution:
For anyone having this issue, if you could post the fix or what's going on here to this point or PM me that would be awesome I'd like to know. I ended up just using PUT to fix this.
Quick Restangular solution:
Build the url template for findByOne like function using Restangular.one(url, _id) where '_id', is the id of the resource you're looking for. .get() goes out and finds that one resource by said id, which you can populate dynamically however you like. Once you have the one resource with GET copy it with Restangular.copy() which is different from angular.copy as it doesn't bind 'this' to the new object. Change what needs to be changed or added in the new object and then perform a .put() on it.
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
var update = Restangular.copy(res);
// update date corporiumId
update.corporiumId = $scope.newBlock;
// submit new doc with altered value
update.put().then(function() {
console.log('updated')
});
console.log(update)
}, function(err) {
console.log('Restangular failed: ', err)
});
Also because mongo uses _id and Restangular uses id you have to add this to your module
angular.module('corporium-mgmnts').config(function(RestangularProvider) {
RestangularProvider.setMethodOverriders(['put', 'patch']);
// setRestangularFields is required for mongodb
RestangularProvider.setRestangularFields({
id: "_id"
});
});
I'm trying to test a Backbone collection's fetch. I'm using Sinon's fake server to set up a fake REST endpoint. The problem is that it seems like the request isn't sending.
I'm using Jasmine with Karma and running it through PhantomJS.
The problem is that the request is apparently not being sent. There aren't any errors but nothing is being logged to the console.
Here's the code:
describe("The Posts collection", function() {
var posts;
var server;
beforeEach(function() {
server = sinon.fakeServer.create();
posts = new PostCollection();
});
afterEach(function() {
server.restore();
});
it("should fetch the posts from the api", function() {
server.respondWith("GET", "/posts",
[200, { "Content-Type": "application/json" },
'{ "stuff": "is", "awesome": "in here" }']);
posts.fetch({
success: function(model, response, options) {
console.log("REQUEST SENT");
}
});
});
});
So as it turns out, I didn't read the docs carefully enough. With the fake server, you need to tell it to respond. I added the following after the call to posts.fetch():
server.respond();
It works perfectly now.
I'm kind of new to Backbone. I need use the data in the server response to a save() method but I'm not sure how to get it. This is the code:
$(".act_btn").on("click", function(){
var act_id = $(this).attr("data-id");
startRecordItem = new StartRecordItem({
activity: act_id,
});
startRecordItem.save({
success: function(response){console.log(response)}
});
/*
recordItem = new RecordItem({
id: ... <---- I have to populate this with the data from the server response.
});
*/
Right now the success function doesn't work at all, what am I missing? I'd like to get an attribute from the JSON response and then use it on the ´new RecordItem´. The save itself works correctly and the response looks like this:
{"activity": 1, "id": 14}
What you're missing is that the first argument of .save. is the attributes that get passed into the model, pre-save. You want to do something more like this:
startRecordItem.save(null, {
success: function(response) {
console.log(response);
}
});
Since Backbone fires a sync event on successful save, you could also do this:
this.listenTo(startRecordItem, 'sync', function() { /* logic here */ });
I am building a small app that uses backbone.js on the client side, node.js/socket.io on the server side, and the connection goes trough websockets only.
Now how would I make my setup if I want to get the template and the data at once.
I do a fetch() in the router, which gets the data and the template. With this I construct my view -> collection -> model.
I do a fetch() in the view itself. (Maybe in the initialize)
===
I want to extend this problem with the following.
Let's say a user browses to http://mysite.com/products and the user is not logged in yet, he is not allowed to view the page. He has to be rerouted to /login.
The problem is I can only verify this on the server, so the server has to send back the correct data whether the user is logged in or not, and backbone.js has to deal with this.
Summarized:
I make a fetch to the server which will send back data + template html.
Backbone.js has to render the template with the data,
or reroute (Backbone.history.navigate('login', {trigger: true})) when the server sends back a flag.
You could use parse method in your Backbone collection for example :
Collections.Products = Backbone.Collection.extend({
url : '/products',
parse : function (response) {
//
// you should return JSON from your server and the object must be smth like
// { template : "<p>template for products</p>", data : productsInJSON }
//
if ( response.template && response.data ) {
this.trigger('template', response.template);
return response.data;
} else {
return response;
}
}
});
Views.Page = Backbone.View.extend({
initialize : function () {
_.bind(this, 'render');
var self = this;
this.collection = new Collections.Products();
this.collection.on('template', function(template) {
self.render(template);
});
},
render: function(template) {
$("div#page").html(template);
}
});
$(function() {
window.app = {};
window.app.view = new Views.Page();
// here you are sending {template:true} to '/products' in your server
window.app.view.collection.fetch( { data : { template : true } } );
});
If you are using socket.io, you should create a new Backbone.sync method for your requests.
It is a little bit out of the Backbone philosophy and the integrated GET, PUT, POST, DELETE methods, so there will be a lot of coding.
You could send a template for unlogged in users with no data for the collection.